vue.js $emit,$on的使用

vue1.0中 vm.$dispatch 和 vm.$broadcast 被弃用,改用$emit,$on

vm.$on( event, callback )

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

vm.$emit( event, […args] )

触发当前实例上的事件。附加参数都会传给监听器回调。

例子:

//父组件
<template>
    <div>
    <children1  v-bind:children1 ="children1 "></children1>
    <children2  v-bind:children2 ="children2 "></children2>
    </div>
</template>
<script>
    import children1 from './children1.vue'
    import children2 from './children2.vue'
    import Vue from 'vue'
    export const event = new Vue();
    export default {
        data: function () {
            return {
                'children1':undefined,
                'children2':undefined,
            }
        },

        mounted: function () {
            let self = this
            //children 设置成obj的目的是正常情况下,他们还需要传给子组件别的值
            self.children1 = {}
            self.children2 = {}
            //因为想要使用$on 或者$emit,必须要使用同一个vue的对象,所以我觉得在他们共同的父组件传给他们比较具有实际的意义,方便多个子组件单独编写在一个页面
            self.children1.event = event
            self.children2.event = event
        },
    }
</script>

父组件使用v-bind:children1 ="children1把同一个event的对象传给做个子组件,

//子组件1
<template>
    <div>
        子组件1:<input type="text" @keyup='change' v-model="text"></input>
    </div>>
</template>
<script>
    export default {
        props:["children1"],
        data: function () {
            return {
                'text':'',
                'Event':undefined,
            }
        },
        methods:{
            change:function () {
                let self = this
                self.Event.$emit('input',self.text)
            }
        },
        mounted: function () {
            let self=this
            self.Event = self.children1.event
        },
    }
</script>

子组件1通过change()来触发$emit,将参数传递给子组件2。

//子组件2
<template>
    <div>
        <h1> 子组件2</h1>>
       <span>子组件1说:{{text}}</span>
    </div>>
</template>
<script>
    export default {
        props:["children2"],
        data: function () {
            return {
                'text':'',
            }
        },
        mounted: function () {
            let self=this
            let Event = self.children2.event
            Event.$on('input',function (data) {
                self.text = data
            })
        },
    }
</script>

子组件2通过绑定$on来监听组件1的值得变化,只要组件1的值随着按键离开的时候就会把这个值传给组件2.

总结:初次看这个用法的时候比较疑惑,主要是我们需要调用或者传递值给不同的组件,每个组件又在不同的页面,因此不知道let  Event = new Vue()这个对象怎么给不同的页面,必须明白只能是在同一个对象上面绑定$on和$emit才会起作用,后来发现只要在他们共同的页面把同一个对象分别传给不同的页面就可以了

二.

   还有一种方式就是直接用VUE导入文件的方式:

版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/lixiwoaini/article/details/80986762

猜你喜欢

转载自blog.csdn.net/lixiwoaini/article/details/80986762