子组件MyStudent.vue
<template>
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生年龄:{{ age }}</h2>
<button @click="sendStudentName">把学生姓名给App</button>
<button @click="unbind">解绑自定义事件</button>
<button @click="death">销毁当前组件的实例(vc)</button>
</div>
</template>
<script>
export default {
name: "MyStedent",
props: ["atguigu"],
data() {
return {
name: "张三",
age: 18,
};
},
methods: {
sendStudentName() {
//触发MyStudent组件实例身上的atguigu事件
this.$emit("atguigu", this.name, 666, 888, 999);
this.$emit("demo");
},
unbind() {
this.$off("atguigu"); //解绑一个自定义事件
this.$off(["atguigu", "demo"]); //解绑多个自定义事件
this.$off(); //解绑所有的自定义事件
},
death() {
this.$destroy(); //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效
},
},
};
</script>
<style>
.student {
background-color: pink;
}
</style>
App.vue
<template>
<div class="app">
<h1>{{ msg }}</h1>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<!-- <MySchool :getSchoolName="getSchoolName" /> -->
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on)(.once只触发一次) -->
<MyStudent v-on:atguigu="getStudentName" @demo="m1" />
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 (第二种写法,使用ref)-->
<!-- <MyStudent ref="student" /> -->
</div>
</template>
<script>
//引入组件
import MySchool from "./components/MySchool.vue";
import MyStudent from "./components/MyStudent.vue";
export default {
name: "App",
components: {
MySchool,
MyStudent,
},
data() {
return {
msg: "你好啊",
};
},
methods: {
getSchoolName(name) {
console.log("App收到了学校名", name);
},
getStudentName(name, ...params) {
console.log("App收到了学生姓名", name, params);
},
m1() {
console.log("demo被触发了");
},
},
// mounted() {
// // this.$refs.student.$on("atguigu", this.getStudentName);//绑定自定义事件
// this.$refs.student.$once("atguigu", this.getStudentName);//绑定自定义事件(一次性)
// },
};
</script>
<style>
.app {
background-color: green;
}
</style>