How to call multiple function with v-on:click

2019-01-16 13:44发布

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.

8条回答
时光不老,我们不散
2楼-- · 2019-01-16 14:20

Separate into pieces.

Inline:

<div @click="f1() + f2()"></div> 

OR: Through a composite function:

<div @click="f3()"></div> 

<script>
var app = new Vue({
  // ...
  methods: {
    f3: function() { f1() + f2(); }
    f1: function() {},
    f2: function() {}
  }
})
</script>
查看更多
仙女界的扛把子
3楼-- · 2019-01-16 14:21

to add an anomymous function to do that may be an alternative:

<div v-on:click="return function() { fn1('foo');fn2('bar'); }()"> </div> 
查看更多
Juvenile、少年°
4楼-- · 2019-01-16 14:25

you can, however, do something like this :

<div onclick="return function()
              {console.log('yaay, another onclick event!')}()" 
              @click="defaultFunction"></div>

yes, by using native onclick html event.

查看更多
beautiful°
5楼-- · 2019-01-16 14:26

Html:

<div id="example">
  <button v-on:click="multiple">Multiple</button>
</div>

JS:

var vm = new Vue({
  el: '#example',
  data: {
    name: 'Vue.js'
  },
  // define methods under the `methods` object
  methods: {
    multiple: function (event) {
      this.first()
      this.second()
    }
    first:  function (event) {
      //yourstuff
    }
    second: function (event) {
      //yourstuff
    }
  }
})

vm.multiple()
查看更多
再贱就再见
6楼-- · 2019-01-16 14:29

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>
查看更多
孤傲高冷的网名
7楼-- · 2019-01-16 14:31

I'm on Vue 2.3 and I can do this:

<div v-on:click="firstFunction(); secondFunction();"></div>
查看更多
登录 后发表回答