1.一种组件间通信的方式,适用于:子组件 ===> 父组件
2.使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)
3.绑定的自定义事件:
第一种方式:在父组件中:
<Student v-on:atguigu="getStudentName" @demo="m1"/>
第二种方式:在父组件中:
<Student ref="student"/>
mounted() {
// 只触发一次
// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件
this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
}
若想让自定义事件只触发一次,可以使用once修饰符,或$once方法
4.触发自定义事件:
this.$emit('atguigu',this.name)
5.解绑自定义事件:
this.$off('atguigu') //解绑一个自定义事件
this.$off(['atguigu','demo']) //解绑多个自定义事件
this.$off()//解绑所有的自定义事件
6.组件上也可以绑定原生DOM事件,需要使用native修饰符:
<Student @click.native="show"/>
7.注意:通过this.$refs.xxx.$on('atguigu',回调函数)绑定自定义事件时,回调要么配置在methods,要么用箭头函数,否则this指向会出问题
<div class="student">
<!-- 组件的结构 -->
<h2>学生姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="SendStudentName">把学生名给app</button>
<button @click="unbind">解绑atguigu事件</button>
<button @click="death">销毁当前student组件的实例对象 vc</button>
</div>
........
methods: {
SendStudentName(){
// 触发student事件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,1,2,3)
// this.$emit('demo')
},
unbind(){
this.$off('atguigu') //解绑一个自定义事件
// this.$off(['atguigu','demo']) //解绑多个自定义事件
// this.$off()//解绑所有的自定义事件
},
death(){
this.$destroy() //销毁了当前student组件的实例,销毁后所有student实例的自定义事件全都不奏效
}
},