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 Answers1

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
},
Peter Krebs
  • 3,831
  • 2
  • 15
  • 29
  • 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') – Hunter Forrester Aug 11 '22 at 11:33
  • In your code you have `health` not `stats.health` so it would be `this[statName]` instead I'm guessing. – Peter Krebs Aug 11 '22 at 11:40
  • @Peter that's right, changing it to this[statName] worked. Thanks guys – Hunter Forrester Aug 11 '22 at 11:42
  • 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]' – SIHEM BOUHENNICHE Aug 11 '22 at 11:44