Vue组件中自定义事件是组件间通信的方式适用于子组件===>父组件通信
自定义事件步骤
1. 父组件中定义事件
第一种方式
<Demo @sendName="test"/>
//
<Demo v-on:sendName="test"/>
methods:{
test(data){
console.log("接受子组件数据",data)
}
}
第二种方式
<Demo ref="demo"/>
mounted(){
this.$refs.Student.$on('自定义事件名',this.test)
}
注意使用this. r e f s . 组件 . refs.组件. refs.组件.on(事件名,回调)绑定自定义事件时,回调方法要么写在methods中,要么使用箭头函数,否则this指向会出问题
2.子组件中使用
<button @click="sendData" />
methods:{
sendData(){
this.$emit('sendName',this.name)
}
}
通过 this.$emit(‘事件名’,数据)触发
3. 解绑事件
methods:{
//解绑事件
unBind(){
this.$off('sendName');
//this.$off();//解绑所有事件
//解绑多个
//this.$off(['sendName','demo']);
},
}