'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}} }}


Solution 1:[1]

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://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/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://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.min.js"></script>

Solution 2:[2]

Array is more effiency your example. You can also use with Array v-for, Filter And Find methods. Also search in array or change names, split or splice.

<div id="app">
  {{ names[number-1] }} <!-- Result =name2. if you need name 2 array index = 1    -->
</div>

new Vue({
  el: "#app",
  data() {
    return {
      number: 2,
      names: ['name1','name2','name3'],
      }
    }
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mahir Alt?nkaya