如何在 vue 中使用 @click 调用多个函数?

2022-08-30 02:06:38

问题:

如何在单个函数中调用多个函数?(又名)?@clickv-on:click

我试过了

  • 带分号的拆分函数:<div @click="fn1('foo');fn2('bar')"> </div>;

  • 使用几种:@click<div @click="fn1('foo')" @click="fn2('bar')"> </div>;

但是如何正确地做到这一点呢?

附言:当然,我总是可以做到的

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

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

但有时这并不好。


答案 1

在 Vue 2.3 及更高版本上,您可以执行以下操作:

<div v-on:click="firstFunction(); secondFunction();"></div>
// or
<div @click="firstFunction(); secondFunction();"></div>

答案 2

首先,您可以使用简短的表示法,而不是为了可读性目的。@clickv-on:click

其次,您可以使用单击事件处理程序来调用其他函数/方法,如@Tushar在上面的评论中提到的那样,因此您最终会得到这样的东西:

<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>