Dynamically access Vue component data variable names

edit: I have used a number in this example which was a bad idea, in the real program I’m not using numbers but names (eg name_abba, name_jef, name_john)

I have 4 variables in my Vue component:

name_1
name_2
name_3
number

Printing the values is done as such:

{{ name_1 }}

How can I change the number in back of the variable, based on the value of the variable number? Or is there a better way to make something like this work?

{{ name_{{number}} }}

Answer

Use the $data option:

new Vue({
  el: "#app",
  data() {
    return {
      name_abba: 'aaa',
      name_jef: 'bbb',
      name_john: 'ccc',
      current: 'john'
    }
  }
});
<div id="app">
  {{ $data[`name_${current}`] }}
</div>

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

It would be better to place your variables in an object instead of on the root so that you don’t have to use $data:

new Vue({
  el: "#app",
  data() {
    return {
      current: 'john',
      name: {
        abba: 'aaa',
        jef: 'bbb',
        john: 'ccc',
      }
    }
  }
});
<div id="app">
  {{ name[current] }}
</div>

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *