1. 一种组件间通信的方式,适用于:子组件 ===> 父组件
2. 使用场景:A 是父组件,B 是子组件,B 想给 A 传数据,那么就要在 A 中给 B 绑定自定义事件(事件的回调在 A 中)。
3. 绑定自定义事件:
(1)第一种方式,在父组件中:`<Demo @atguigu="test"/>` 或 `<Demo v-on:atguigu="test"/>`
代码实现:
子组件Student.vue:
<template>
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">点我将学生姓名传给父组件App</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男'
}
},
methods: {
sendStudentName() {
this.$emit('atguigu', this.name);
}
}
}
</script>
<style scoped>
.student {
background-color: orange;
padding: 5px;
margin-top: 30px;
}
</style>
父组件App.vue:
<template>
<div class="app">
<h1>{{msg}}, 该学生的名字是:{{studentName}}</h1>
<!-- 通过父组件给子组件 绑定一个自定义事件 实现子组件给父组件传递数据(第一种写法:使用@或v-on) -->
<Student v-on:atguigu="getStudentName" />
</div>
</template>
<script>
import Student from './components/Student'
export default {
name: 'App',
components: { Student },
data() {
return {
msg: '你好啊!',
studentName: ''
}
},
methods: {
getStudentName(name) {
this.studentName = name;
}
}
}
</script>
<style scoped>
.app {
background: gray;
padding: 5px;
}
</style>
运行后页面显示如下:
点击页面中button后显示(获取子组件中学生姓名,并且显示在页面中):
(2)第二种方式,在父组件中:
<Demo ref="demo"/>
......
mounted(){
this.$refs.demo.$on('atguigu',this.test)
}
```
代码实现:
父组件App.vue:
<template>
<div class="app">
<h1>{{msg}}, 该学生的名字是:{{studentName}}</h1>
<Student ref="student" />
</div>
</template>
<script>
import Student from './components/Student'
export default {
name: 'App',
components: { Student },
data() {
return {
msg: '你好啊!',
studentName: ''
}
},
methods: {
getStudentName(name) {
this.studentName = name;
}
},
mounted() {
// this.$refs.xxx.$on('atguigu',回调) atguigu事件
this.$refs.student.$on('atguigu', this.getStudentName);
}
}
</script>
<style scoped>
.app {
background: gray;
padding: 5px;
}
</style>
子组件的代码和第一种方式的代码相同,且运行效果相同。
(3) 若想让自定义事件只能触发一次,可以使用`once`修饰符,或`$once`方法。
4. 触发自定义事件:`this.$emit('atguigu',数据)`
5. 解绑自定义事件`this.$off('atguigu')`
<template>
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">点我将学生姓名传给父组件App</button>
<button @click="unbind">点击解绑atguigu事件</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男'
}
},
methods: {
sendStudentName() {
this.$emit('atguigu', this.name);
},
unbind() {
this.$off('atguigu'); // this.$off('') 表示解绑被绑定的自定义事件
}
}
}
</script>
<style scoped>
.student {
background-color: orange;
padding: 5px;
margin-top: 30px;
}
</style>
6. 组件上也可以绑定原生 DOM 事件,需要使用`native`修饰符。
7. 注意:通过`this.$refs.xxx.$on('atguigu',回调)`绑定自定义事件时,回调<span style="color:red">要么配置在 methods 中</span>,<span style="color:red">要么用箭头函数</span>,否则 this 指向会出问题!