组件自定义事件
- 是一种组件间通信的方式,适用于:子组件===>父组件
- 使用场景:子组件向父组件传递数据,在父组件中绑定事件回调,使用子组件时绑定自定义事件
- 组件绑定原生DOM事件需在事件名后添加.native事件修饰符
-
<组件名 @click.native="事件名"></组件名>
绑定
子组件向父组件传值
通过props方法实现
父组件
<School :sendSchoolName="sendSchoolName"></School>
sendSchoolName(names) {
console.log('sendSchoolName被调用了', names)
},
子组件
<button @click="getSchoolName">点击传递学校名给App</button>
props:['sendSchoolName'],
methods:{
getSchoolName(){
this.sendSchoolName(this.names)
}
}
绑定自定义事件实现
@on/v-on方法
父组件
<Student v-on:send="sendStudentName"></Student>
<Student @send="sendStudentName"></Student>
methods: {
sendStudentName(names) {
console.log('sendStudentName被调用了', names)
}
},
子组件
<button @click="sendStudentName">点击传递学生姓名给App</button>
methods:{
sendStudentName(){
// 触发Student组件实例上的send事件
this.$emit('send',this.names)
}
}
ref方法
- 使用该方法时,回调函数最好配置在methods中以避免this指向问题
- 如若需要直接将回调函数配置在ref方法中时,该回调函数写成箭头函数以避免this指向问题
父组件
<Student ref="student"></Student>
methods: {
sendStudentName(names) {
console.log('sendStudentName被调用了', names)
}
},
mounted() {
this.$refs.student.$on('send',this.sendStudentName)
// 控制代码只能触发一次
// this.$refs.student.$once('send',this.sendStudentName)
}
子组件
<button @click="sendStudentName">点击传递学生姓名给App</button>
解绑
- 父组件不进行代码操作,在子组件中进行定义和调用
子组件
<button @click="unbind">解绑事件</button>
methods:{
unbind(){
// 解绑一个自定义事件
this.$off('send')
//解绑多个自定义事件
// this.$off(['send','事件名2'])
// 解绑全部自定义事件
// this.$off()
}