Reputation: 1290
Problem: I need to set a vue component's event handler equal to the return value of another method.
This JavaScript runs on click.
<!-- pseudo code -->
<input type="button" @click="count + 1">
Method is invoked on click.
<!-- pseudo code -->
<input type="button" @click="addToCount">
...
<script>
function addToCount () {
count + 1
}
</script>
But this will invoke getAddToCountHandler
on click, not addToCount
.
<!-- pseudo code -->
<input type="button" @click="getAddToCountHandler()">
...
<script>
function getAddToCountHandler () {
return function addToCount () {
count + 1
}
}
</script>
The following is closer to what I am trying to do, with some variables stored in a closure.
<!-- pseudo code -->
<input type="button" @click="getHandler(0)">
...
<script>
function getHandler (param) {
let storedParam = param
return function () {
storedParam += 1
console.log(storedParam)
}
}
</script>
Upvotes: 1
Views: 1358
Reputation: 1
You should run the return function as follows by adding ()
like :
<input type="button" @click="getAddToCountHandler()()">
or
function getAddToCountHandler () {
return function addToCount () {
count + 1
}()
}
let app=new Vue({
el: "#app",
data:function() {
return {
count: 0
}
},
methods: {
getAddToCountHandler() {
let that=this;
return function addToCount() {
console.log(that.count)
that.count =that.count+1
}()
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="button" @click="getAddToCountHandler()" value="increment" /> {{count}}
</div>
Upvotes: 1