3

I would like to have a property dynamically accessed with a variable.

For example, I have :

data(){
    redsection : '',
    bluesection : '',
},
methods(){
     changeColor(color, val){
          this.{color+"section"} = val;
     }
}

And what I'm trying to do it have a function in the view:

<button @click="changeColor("blue", "bar")>blue</button>
<button @click="changeColor("red", "bar")>blue</button>

2 Answers 2

8

Use an indexer.

this[color+"section"] = val;

Here is an example.

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

Comments

2

You could also change it up a bit if you want to make it prettier, like this:

data(){
     section: {
          red : 'red',
          blue : 'blue'
     }
},
methods(){
     changeColor(color, val){
          this.section[color] = val;
     }
}

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.