0
votes

I am building a web app using Vue 2.6.x. In the prototype that was created we have a line like this repeated many times:

<label class="title">On Time</label><span class="score float-right">Score: {{ score.ap_ontime }}

The only part of this whole line that changes is the data within the {{ }}. I would like to turn this into a component that I can call many times. For example:

<MyLabel title="On Time" score="score.ap_ontime" />

...so that I don't have to type this score interpolation over and over in a long HTML file. I know how pass props to the component and add text to the template of the component:

<template>
...
<label class="title">{{title}}</label>
...
</template>

..but what I can't figure out is how to take a string (e.g.score.ap_ontime) and have the template inject something that will render that value from a score plain old JavaScript object that exists in the application and is imported into the template. The original code I show at the top of this post renders fine and reacts to changes in the JavaScript object I just can't figure out how to do this in a component that creates HTML and Vue template syntax based on props.

1
Are you just asking about a binding? If so it's :score="score.ap_ontime", notice the :Dan

1 Answers

0
votes

Your new component should look something like this:

<template>
  <label class="title">{{ caption }}</label>
  <span class="score float-right">Score: {{ onTime }}</span>
</template>

<script>
export default
{
  name: 'MyNewComponent',
  props:
  {
    caption:
    {
      type: String,
      default: ''
    },
    onTime:
    {
      type: [String, Number],
      default: 0
    }
  }
}
</script>

Then you can call your component in this way:

<my-new-component :caption="Big title" :on-time="score.ap_ontime" />