Home » vue » accessing vue-model properties using ${}

accessing vue-model properties using ${}

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a tiny snippet that works correctly when I use :src="labels[index]", but my code is growing and I will need to use ${app.labels[index]}. I can do just ${app.labels}, but once I add the [index] part, it breaks. Can someone tell me how to add that inside the brackets?

new Vue({
  el: "#app",
  data: {
    images: [],
        labels: [],
          form: {
            dir: "",
            fileItems: [] // An array containing objects of type: {id: number, file: File, dataUrl: [base64 encoded file string], caption: string'}
          },
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
      <div class="image-wrap"><img style="max-height: 430px;" :src="${app.labels[index]}" /></div>
</div>

Answers:

In Vue when you use : in a prop you are basically telling Vue

Please, interpret this expression side as javascript

An example:

<super-aweosme-component :a="1 + 1" />

Will result in the prop a being 2 (because it was interpreted as javasript).

When you don’t use : in a component prop you are telling Vue

Please, interpret this as plain text

An example

<super-aweosme-component a="1 + 1" />

Will result in the prop a being literally 1 + 1 (string). So you can change :src="${images.labels[index]}" to just :src="images.labels[index]" (of course, apply the changes mentioned above)

Adition

You have app.labels[index]. app doesn’t exist in the template context. You have in that context images, labels and form (of course, there are attributes in that context but not important for this part)