App.vue
<template>
<div id="app">
我是App根组件
<hr />
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<School :getSchoolName="getSchoolName"></School>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 第一种写法使用@或v-on-->
<Student @yhan="getStudentName" @yh="m1"></Student>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 第2种写法,使用ref-->
<!-- <Student ref="student"></Student> -->
</div>
</template>
<script>
import Student from "./components/Student.vue";
import School from "./components/School.vue";
export default {
name: "App",
components: {
Student,
School,
},
methods: {
getSchoolName(name) {
console.log("App根组件收到了School学校传来的姓名", name);
},
getStudentName(name, ...params) {
console.log("App收到了学生名", name, params);
},
m1() {
console.log("yh事件被触发了");
},
},
mounted() {
// 绑定自定义事件
// this.$refs.student.$on("yhan", this.getStudentName);
// 绑定自定义事件(一次性)
// this.$refs.student.$once("yhan", this.getStudentName);
},
};
</script>
<style>
#app {
width: 300px;
height: 400px;
background-color: aliceblue;
}
</style>
School.vue
<template>
<div>
<h2>姓名:{{ name }}</h2>
<h2>地址:{{ address }}</h2>
<button @click="sendSchoolName">点我向App组件发送名字</button>
</div>
</template>
<script>
export default {
name: "School",
props: ["getSchoolName"],
data() {
return {
name: "尚硅谷",
address: "河南省",
};
},
methods: {
sendSchoolName() {
this.getSchoolName(this.name);
},
},
};
</script>
<style scoped>
div {
width: 295px;
height: 150px;
padding-top: 20px;
background-color: darkorange;
}
</style>
Student.vue
<template>
<div>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="sendStudentName">点我向App组件发送名字</button>
<button @click="unbind">解绑yhan事件</button>
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
name: "千玺",
age: 18,
};
},
methods: {
sendStudentName() {
// 触发Student组件实例身上的yh事件
this.$emit("yhan", this.name, 1216, 1111);
this.$emit("yh");
},
// 解绑,
unbind() {
this.$off("yhan"); //适用于解绑一个自定义事件
// this.$off(["yhan", "yh"]);
this.$off(); //所有的自定义事件全被解绑
},
},
};
</script>
<style scoped>
div {
width: 295px;
height: 150px;
padding-top: 20px;
background-color: brown;
}
</style>