DevonDahon
DevonDahon

Reputation: 8350

VueJS: Set variable name using string

Is it possible to set a variable myvar using a string in the example below ?

<script>
export default {
    data() {
        return {
            myvar: 'foo'
        };
    }
}
</script>

I tried this which didn't work:

eval('myvar'): 'foo'

Upvotes: 4

Views: 14301

Answers (2)

James Whiteley
James Whiteley

Reputation: 3468

To change data, you just need to modify it like you would any other mutable variable. It depends how your component is set up. Looking at the docs (https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties), one way of doing it is like this (modified example from the above link):

const vue = new Vue({
  el: '#app',
  data: {
    myvar: 'foo'
  },
  template: '<div>{{ myvar }}</div>'
})

vue.myvar = 'bar'
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

If you want to do it from a method (e.g. calling a method from within a template), refer to it with the this keyword:

const vue = new Vue({
  el: '#app',
  data: {
    myvar: 'foo'
  },
  template: '<div><div>{{ myvar }}</div><button @click="changeMe">Click Me</button></div>',
  methods: {
    changeMe() {
      this.myvar = 'bar'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Upvotes: -3

Derek Pollard
Derek Pollard

Reputation: 7165

Here is a very crude and basic example of how you would accomplish something like this:

new Vue({
  el: "#app",
  data() {
    return {
      myVar: 'hello'
    }
  },
  methods: {
    changeVal(varName, newValue) {
      this[varName] = newValue;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{myVar}}
  <button @click="changeVal('myVar', 'world')">change myVar</button>
</div>

Here, we are utilizing a method that takes the name of the variable and the value to change it to - then passing it to the current vue model instance (represented by this inside of methods) to modify the value of the dynamic variable name.

Upvotes: 5

Related Questions