How to call multiple functions with @click in vue?
Question:
How to call multiple functions in a single @click? (aka v-on:click
)?
I tried
Split functions with a semicolon:
<div @click="fn1('foo');fn2('bar')"> </div>
;Use several
@click
:<div @click="fn1('foo')" @click="fn2('bar')"> </div>
;
but how to do it properly?
P.S.: For sure I always can do
<div v-on:click="fn3('foo', 'bar')"> </div>
function fn3 (args) {
fn1(args);
fn2(args);
}
But sometimes this isn't nice.
Solution 1:
On Vue 2.3 and above you can do this:
<div v-on:click="firstFunction(); secondFunction();"></div>
// or
<div @click="firstFunction(); secondFunction();"></div>
Solution 2:
First of all you can use the short notation @click
instead of v-on:click
for readability purposes.
Second You can use a click event handler that calls other functions/methods as @Tushar mentioned in his comment above, so you end up with something like this :
<div id="app">
<div @click="handler('foo','bar')">
Hi, click me!
</div>
</div>
<!-- link to vue.js !-->
<script src="vue.js"></script>
<script>
(function(){
var vm = new Vue({
el:'#app',
methods:{
method1:function(arg){
console.log('method1: ',arg);
},
method2:function(arg){
console.log('method2: ',arg);
},
handler:function(arg1,arg2){
this.method1(arg1);
this.method2(arg2);
}
}
})
}());
</script>
Solution 3:
If you want something a little bit more readable, you can try this:
<button @click="[click1($event), click2($event)]">
Multiple
</button>
To me, this solution feels more Vue-like hope you enjoy