1. 一种组件间通信的方式,适用于:子组件 ===> 父组件
2.使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
3.绑定自定义事件:
1)第一种方式,在父组件中:
<Demo @atguigu="test"/>或<Demo v-on:atguigu="test"/>
2)第二种方式,在父组件中:
<Demo ref="demo"/>
mounted(){
this.$refs.xxx.$on('atguigu',this.test)
}
3.若想让自定义事件只能触发一次,可以使用once
修饰符,或$once
方法。
4.触发自定义事件:this.$emit('atguigu',数据)
5.解绑自定义事件this.$off('atguigu')
6.
组件上也可以绑定原生DOM事件,需要使用```native```修饰符。
## 安装全局事件总线:
new Vue({
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
},
})
使用事件总线:
1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){
demo(data){......}
}
mounted() {
this.$bus.$on('xxxx',this.demo)
}
2. 提供数据:```this.$bus.$emit('xxxx',数据)```
3. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。