天下无坑

天下无坑


v-on与vm.$on的区别

[vue中的事件监听之——v-on vs .$on](https://www.cnblogs.com/surfer/p/9815692.html "vue中的事件监听之——v-on vs .$on")

跟着视频中老师的教学视频学vue的时候,看很多时候都用@(v-on)来监听子级emit的自定义事件,但在 [bus总线](https://www.jianshu.com/p/a544728bf596 "bus总线") 那块,又用.$on来监听bus自身emit的事件,v-on之间似乎相似但又不同,今天对照vue官网api学习并coding了相关代码,两者的用法与比较描述如下。

v-on $on
可监听普通dom的原生事件;<br>可监听子组件emit的自定义事件; 监听当前实例的自定义事件

vue官网相关说明截图:

由此可见,想监听vue实例自身自定义事件,只能用.$on并且这是vue实例的方法,不能用在普通dom上;

v-on用在在普通dom标签上,可以监听原生事件;用在vue组件标签上,可以监听子组件emit的自定义事件;

@startuml
title $emit 触发自定义事件流程

|子组件|
start
:子组件$emit(EVENT,arg);
|#AntiqueWhite|父组件|
if (是否有v-on:EVENT=&quot;FN&quot;?) then (是)
:执行FN方法|
endif
|子组件|
if (是否有$on(EVENT,FN)?) then (是)
:执行FN方法|
endif
stop
@enduml

具体代码实践如下:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset=&quot;UTF-8&quot;&gt;
        &lt;title&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div id=&quot;app&quot;&gt;
            &lt;!--监听子组件emit的自定义事件--&gt;
            &lt;child @change=&quot;handleChange&quot;&gt;child1&lt;/child&gt;
            &lt;child @change=&quot;handleChange&quot;&gt;child2&lt;/child&gt;
            &lt;child @change=&quot;handleChange&quot;&gt;child3&lt;/child&gt;
        &lt;/div&gt;
    &lt;/body&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;../js/vue.js&quot; &gt;&lt;/script&gt;
    &lt;script&gt;
        var Child = {
            template:`&lt;div @click='handleClick'&gt;
                &lt;slot&gt;&lt;/slot&gt;
            &lt;/div&gt;`,
            methods:{
                handleClick(){
                    this.$emit( 'change' );
                }
            },
            mounted(){
                //监听当前实例的自定义change事件
                this.$on( 'change',function(){
                    console.log( 'child-change-event-handler' );
                } );
            }
        };
        var vm = new Vue({
            el:'#app',
            components:{
                Child,
            },
            methods:{
                handleChange(){
                    console.log( 'parent-change-event-handler' );
                },
                handleClick(){
                    console.log( 'handleClick' );
                }
            },
            mounted(){
                this.$on( 'change',this.handleChange );
            }
        });
    &lt;/script&gt;
&lt;/html&gt;

页面列表

ITEM_HTML