3

How can I assign data to a dynamic variable.

What I'm trying to achieve is this:

My vue data variable:

test: '',

Adding a click

<div @click="assignData(test)"

Method:

assignData(value) {
   // Now I don't want this
   this.test = 'lorem..';

   // Instead I want something like this
  value = 'new value for test';

  // Or
  this.value = 'new value for test';
}

Now obviously this is not gonna work, but I hope you'll get the idea.

I need to change many variables and I don't want to add all the variables in the function like this

assignData(value) {

   this.test = 'lorem..';
   this.anotherVar = 'ipsum';
   this.newTest = '....';       
}

3 Answers 3

5

You could send the property you want to change with the function.

<div @click="assignData('test', 'new value for test)">

and then in your code

 assignData(prop,val) {
        this[prop] = val;
      console.log(this.test);
    }

Here is a snippet from jsfiddle: https://jsfiddle.net/49gptnad/6447/

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

4 Comments

How does that work when I want to target a key in an object? Example: assignData('test.user.name', 'new value for name)
This code won't work for that. You would need to modify it. Is there a reason you don't want to use multiple functions one for each object? For example updateUser - updateCar - updateHome and have explicit statements what is mapped to what.
Also where are you getting the values? From an input or http request or? If its inputs, then v-model might be the solution you are looking for. jsfiddle.net/49gptnad/6453
I need to assign Pixi objects everytime I click depending on the value. But I guess It can't be shortened.
3

assignData(key, value) {
  this[key] = value;
}

You'll have to specify the variable you're assigning when you activate it with the click caller.

Comments

2

You should use either vm.$set( target, key, value ) or Vue.set( target, key, value )

Vue.set docs

vm.$set docs

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.