Vue.js 2.0 中#$on与$emit如何使用之实例讲解

先对两个方法来一波解释

vm.$on(event,callback)

参数:
{string | Array} event (数组只在 2.2.0+ 中支持)
{Function} callback

用法:
监听当前实例上的自定义事件。事件可以由vm.$emit触发。回调函数会接收所有传入事件触发函数的额外参数。

示例:

vm.$on('test', function (msg) {   
console.log(msg) 
}) 
vm.$emit('test', 'hi') 
// => "hi"

vm.$emit(event,[args])

参数:
{string} event
[…args]
触发当前实例上的事件。附加参数都会传给监听器回调。

上面是官方的api,很简洁,粗略一看很容易误解,这里主要是$on的用法,这里回过头去看一下$on的用法,$on是监听当前实例上的自定义事件,这个自定义事件可以由$emit来触发,$on回调函数接收的msg便是$emit方法第二个参数传过来的值。当然你也可以在回调函数里不使用msg参数而执行其他操作。

下面是实例:

再定义一个组件(一个计数的组件)

Vue.component('simple-com',{
    template:'<button v-on:click="incresone">{{count}}</button>',
    data:function(){
        return {
            count:0
        }
    },
    methods:{
        incresone:function(){
            this.count+=1
            //监听自定义的事件
            this.$on('increment',function(msg){
                //获取$emit方法传递的第二个参数
                console.log(msg);
                alert("1");
            })
            //触发自定义的事件
            this.$emit('increment',this.count)
        }
    }
   })

再使用组件

    <simple-com v-on:increment="incretol"></simple-com>
    <simple-com v-on:increment="incretol"></simple-com>
    <simple-com v-on:increment="incretol"></simple-com>
    <p>{{total}}</p>

实例化vue的代码

var vm = new Vue({
    el:"#app",
    data: {
        total:0
    }
    methods:{
        incretol:function(){
                this.total+=1
            }
    }
})

当我点击计数的时候,$on监听increment事件,当increment事件执行时,便会弹出1,然后再继续执行后面的代码。

这里写图片描述

当然$emit方法传递的第二个参数也能获取到

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_35616850/article/details/78581429