1

I have a button that activates the raiseStat() function. I want to pass through the name of an existing variable so that a function can then modify that specific variable.

The button:

<button @click="raiseStat(health)">Add</button>

The data I want to modify:

data(){
    return{
        health: 1,
    }
},

The function:

 methods: {
    raiseStat(statName){
      statName++
    },

},

When I console.log the variable within the function it says '1' which makes sense, I'm passing through the value of the variable, not the name.

So how would I refer to the name of this variable rather than the value?

Thanks

1

1 Answer 1

4

You can declare stats as object and then access to the 'health' key :

<button @click="raiseStat('health')">Add</button>
data(){
    return{
        health: 1,
    }
},
methods: {
    raiseStat(statName){
      this[statName] += 1
},
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply @SIHEM ! I actually get an error clicking the button after updating this: Uncaught TypeError: Cannot read properties of undefined (reading 'health')
In your code you have health not stats.health so it would be this[statName] instead I'm guessing.
@Peter that's right, changing it to this[statName] worked. Thanks guys
So it should work, look at the data i've changed the declaration of 'health' to be included inside an object called 'stats', are you sure to access the 'stats[statName]' and not directly 'this[statName]'

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.