Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}} }}
like image 344
VandeputHendrik Avatar asked Sep 29 '26 20:09

VandeputHendrik


1 Answers

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>
like image 198
Dan Avatar answered Oct 02 '26 10:10

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!