vue2-非父子组件通信-自定义事件

在组件中使用

1.在main.js中定义一个空的vue实例,在data中定义一个 Bus:new Vue()

new Vue({
    el: '#app',
    data:{
        Bus: new Vue()
    },
    router: router,
    render: h => h(App)
})

2.在任意组件中发起自定义事件

myEmit(){
    this.$root.Bus.$emit('test-click', 123)
}
  • 这里传递的是一个字符串,其实也可以传递对象,例如:
this.$root.Bus.$emit('test-click', {name:'Timo',height:'1.5'})

3.在任意组件中,接收自定义事件

mounted(){
    this.$root.Bus.$on('test-click', val => {
    console.log(val)
    })
}

4.在不需要的时候,我们最好删掉这个自定义事件

delEmit(){
    this.$root.Bus.$off('test-click')
}

猜你喜欢

转载自blog.csdn.net/li522021642/article/details/80233188