【Vue2.0学习】—组件的自定义事件(五十八)
- 一种组件间通信的方式:适用于子组件—>父组件
-
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要A给B绑定自定义事件,事件的回调在A中
绑定自定义事件:
- 第一种方式:在父组件中
第二种方式:在父组件中:<Demo @stu="test"/>或<Demo v-on:stu="test"/>
<Demo ref="demo"/>
……
mounted(){
this.$refs.XXX.$on('stu',this.test)
}
-
若想让自定义事件只触发一次,可以使用once修饰符或$once方法
触发自定义事件:
解绑自定义事件:this.$emit('stu',数据)
this.$off('stu')
- 组件上也可以绑定原生
事件,需要使用DOM
native
修饰符
注意:通过
绑定自定义事件时,回调要么配置在this.$refs.XXX.$on('native',回调)
中,要么用箭头函数否则methods
指向会出问题this
<template>
<div class="container">
<h1>{{msg}}</h1>
<School :getSchoolName="getSchoolName" />
<!-- 意思是说:给Student组件的实例对象vc身上绑定了一个事件,事件名字叫stu,有人触发了这个事件demo函数就会调用-->
<!-- <Student v-on:stu="demo"/> -->
<!-- 通过父组件给子组件绑定一个自定义事件实现:子传父传递数据(使用@或者v-on) -->
<!-- <Student v-on:stu="getName"/> -->
<Student @stu="getName"/>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据使用ref -->
<!-- <Student ref="student"/> -->
<!-- <Student @:stu="getName" @demo="m1" /> -->
</div>
</template>
<script>
import Student from './components/Student.vue'
import School from './components/School.vue'
export default {
name: 'App',
data() {
return {
msg: '你好鸭'
}
},
components: {
School,
Student
},
methods: {
getSchoolName(name) {
console.log('APP收到名字了', name)
},
getName(name) {
console.log('APP收到学生名字了', name)
}
// m1() {
// console.log('demo事件触发了')
// }
},
mounted() {
// this.$refs.student.$on('stu',this.getName)
//触发一次
// this.$refs.student.$once('stu',this.getName)
}
}
</script>
<style scoped>
.container {
background-color: pink;
padding: 5px;
}
</style>
<template>
<div class="box">
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生名给APP</button>
<button @click="unbind">解绑学生事件</button>
</div>
</template>
<script>
export default {
name:'Student',
data(){
return{
name:'王同学',
age:20
}
},
methods:{
sendStudentName(){
//触发Student身上的stu 事件
this.$emit('stu',this.name)
// this.$emit('demo')
},
unbind(){
//用于解绑一个事件
this.$off('stu');//解绑一个事件
//this.$off(['stu','demo'])//解绑多个事件
// this.$off()//解绑所有的事件
}
}
}
</script>
<style scoped>
.box{
background-color: skyblue;
}
</style>