目录
顾名思义,是用于组件之间的自定义事件,下面我将用3个例子去说明(父子组件的通信问题)
(1)组件自定义绑定
student.vue代码
<template>
<div class="student">
<h2>学生姓名:{{ studentName }}</h2>
<h2>学生年龄:{{ studentAge }}</h2>
<button @click="sendStudentName">把学生的姓名给App</button>
</div>
</template>
<script>
export default {
name: "Student",
props: ["getStudentName"],
data() {
return {
studentName: "刘家奕",
studentAge: 19,
};
},
methods: {
sendStudentName() {
this.getStudentName(this.studentName);
},
},
};
</script>
<style>
.student {
background-color: lightblue;
padding: 5px;
}
</style>
app.vue的代码为
<template>
<div class="app">
<h2>{{ msg }}</h2>
<!-- /第一种方法: 通过props -->
<Student :getStudentName="getStudentName" />
<!-- 第二种方法: 自定义组件 简写形式为 <School @liujiayi="getSchoolName" /> -->
<!-- <School v-on:liujiayi="getSchoolName" /> -->
<!-- 第三种方法:ref实现 -->
<School ref="school" />
</div>
</template>
<script>
import Student from "./components/Student";
import School from "./components/School";
// import { computed } from "@vue/runtime-core";
export default {
name: "App",
components: {
Student,
School,
},
data() {
return {
msg: "你好呀",
};
},
methods: {
getStudentName(name) {
console.log("app得到了学生的名字为", name);
},
getSchoolName(name) {
console.log("app得到了学校的名字为", name);
},
},
mounted() {
this.$refs.school.$on("liujiayi", this.getSchoolName);
// $on是当什么时候的意思,在此处是当自定义组件被触发时
},
};
</script>
<style>
.app {
background-color: gray;
padding: 5px;
}
</style>
school.vue代码为:
<template>
<div class="school">
<h2>学校名称:{{ schoolName }}</h2>
<h2>学校地址:{{ address }}</h2>
<button @click="sendSchoolName">把学校的名字给App</button>
</div>
</template>
<script>
// import { emit } from "process";
export default {
name: "School",
data() {
return {
schoolName: "南昌航空大学",
address: "江西",
};
},
methods: {
sendSchoolName() {
this.$emit("liujiayi", this.schoolName);
},
},
};
</script>
<style>
.school {
background-color: yellow;
padding: 10px;
margin-top: 30px;
}
</style>
3种方法在app.vue里有注释
网页效果:
(2)组件自定义的解绑
见代码school.vue
<template>
<div class="school">
<h2>学校名称:{{ schoolName }}</h2>
<h2>学校地址:{{ address }}</h2>
<button @click="sendSchoolName">把学校的名字给App</button>
<button @click="notbind">取消绑定</button> //******************************
</div>
</template>
<script>
// import { emit } from "process";
export default {
name: "School",
data() {
return {
schoolName: "南昌航空大学",
address: "江西",
};
},
methods: {
sendSchoolName() {
this.$emit("liujiayi", this.schoolName);
},
//*******************************************
notbind() {
this.$off("liujiayi");
},
},
};
</script>
<style>
.school {
background-color: yellow;
padding: 10px;
margin-top: 30px;
}
</style>
改动部分我用*标记了
以上是解绑一个自定义组件的方法
如果有多个自定义组件怎么办?
我们可以写成这样:
还有一种更加粗暴的方法: