4

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'
7
  • 1
    you can use this['myvar'] = 'foo'; Commented Apr 15, 2019 at 14:34
  • @DerekPollard I get a syntax error if I do that : Unexpected keyword 'this' Commented Apr 15, 2019 at 14:37
  • where are you using this at? you should probably be doing it in a method Commented Apr 15, 2019 at 14:38
  • I'm just wondering if it's possible to do it. Commented Apr 15, 2019 at 14:43
  • Yeah it's possible for sure, in what scope are you trying to set the variable? Show us an example. Commented Apr 15, 2019 at 14:47

2 Answers 2

5

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.

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

Comments

-3

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>

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.