6

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}} }}
2
  • Any time you have variables with a numeric suffix you probably wanted an array. Commented Mar 7, 2021 at 14:23
  • In the example I'm using a number, in the actual code I'm not using numbers :) Commented Mar 7, 2021 at 14:23

2 Answers 2

10

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Maybe using a number as example was a bad idea, a more accurate example would be variables: "name_jef" and "name_john" and the parts "jef" and "john" would be stored in variable "extra". How could I achieve name_{extra} ?
My answer already works for strings too. Did you try it? I've changed my examples to make this exceptionally clear.
I've indeed managed to get it to work. Even tho it's probably not the perfect solution, it's the best I could think of for my edge case (the example is way to generic). Thanks!
Is there a Vue3 equivalent of this?
0

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'],
      }
    }
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.