Sergey Panfilov Sergey Panfilov - 4 months ago 66
Javascript Question

How to call multiple function with v-on:click

How to call a multiple functions in single

v-on
event?
No difference: click, focus or whatever?

Something like:

<div v-on:click="fn1('foo');fn2('bar')"> </div>


Or may be:

<div v-on:click="fn1('foo')"
v-on:click="fn2('bar')"> </div>


How to do it right?

UPDATE: Yes, of course I always can do

<div v-on:click="fn3('foo', 'bar')"> </div>

function fn3 (args) {
fn1(args);
fn2(args);
}


But that's really ugly.

Answer

First of all you can use the short notation @click instead of v-on:click for readability purposes.

Second You can use a handler that calls other functions 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>