3👍
This:
@click="{{test.method}}"
needs to be this:
@click="test.method"
You don’t need the braces. {{ ... }}
is used to output text into the resulting HTML. Within a v-bind
or v-on
you just write the expression directly, without the {{ ... }}
.
Then this:
tests: [
{ name: "add", method:this.add()},
{ name: "subtract", method:this.subtract()}
]
needs to be this:
tests: [
{ name: "add", method: this.add },
{ name: "subtract", method: this.subtract }
]
or alternatively:
tests: [
{ name: "add", method: () => this.add() },
{ name: "subtract", method: () => this.subtract() }
]
The problem with the existing version is it will invoke add
and subtract
immediately, within the data
function. The values for method
will be set the the return values of those functions, which will be undefined
in this case.
In my first suggestion I’ve just got rid of the ()
, so they won’t be invoked immediately. Instead a reference to the functions will be assigned to method
. Vue automatically binds this
, so there’s no risk of the this
being dropped.
In the second variation I’ve wrapped them in arrow functions. Again this avoids the problem of invoking them immediately. In this scenario there’s no real need to wrap them but it can be more flexible in general. A little care has to be taken to ensure a correct this
value, this wouldn’t have worked if I’d used normal functions instead of arrow functions.