22_组件自定义事件
App.vue
<template>
<div>
<img src="./assets/logo.png" alt="logo" />
<School></School>
<!-- 第一种写法 once 就生效一次 子给父传递数据-->
<Student v-on:atguigu.once="getStudentName"></Student>
<!-- <Student @atguigu="getStudentName"></Student> -->
<!-- 第二种写法 子给父传递数据-->
<!-- <Student ref="student" /> -->
</div>
</template>
<script>
//引入组件
import School from "./components/School";
import Student from "./components/Student";
export default {
name: "App",
components: {
School,
Student,
},
methods: {
getStudentName(name) {
console.log("收到的学生名:", name);
},
},
/* 和第二种相匹配
mounted() {
//可以等3s再执行
setTimeout(() => {
this.$refs.student.$on("atguigu", this.getStudentName); //绑定自定义事件
//触发一次
//this.$refs.student.$once("atguigu", this.getStudentName); //绑定自定义事件
}, 3000);
}, */
};
</script>
<style></style>
Student.vue
<template>
<div>
<h2>学生名称:{{name}}</h2>
<h2>学生年龄: {{age}}</h2>
<button @click="sendStudentName">把学生名给App</button>
</div>
</template>
<script>
export default{
name:'Student', //变量 一般和文件名一样
data() {
return {
name: "张三",
age: 18,
};
},
methods:{
sendStudentName(){
//触发student组件实例身上的atguigu事件
this.$emit('atguigu',this.name)
}
}
};
</script>
<style>
</style>
解绑自定义事件
App.vue
<template>
<div>
<img src="./assets/logo.png" alt="logo" />
<School></School>
<!-- 第一种写法 once 就生效一次 子给父传递数据-->
<Student v-on:atguigu="getStudentName" @demo="m1"></Student>
</div>
</template>
<script>
//引入组件
import School from "./components/School";
import Student from "./components/Student";
export default {
name: "App",
components: {
School,
Student,
},
methods: {
getStudentName(name) {
console.log("收到的学生名:", name);
},
m1(){
console.log(111);
}
},
};
</script>
<style></style>
Student.vue
<template>
<div>
<h2>学生名称:{{ name }}</h2>
<h2>学生年龄: {{ age }}</h2>
<button @click="sendStudentName">把学生名给App</button>
<button @click="unbind">解绑atguigu事件</button>
</div>
</template>
<script>
export default {
name: "Student", //变量 一般和文件名一样
data() {
return {
name: "张三",
age: 18,
};
},
methods: {
sendStudentName() {
//触发student组件实例身上的atguigu事件
this.$emit("atguigu", this.name);
this.$emit("demo");
},
unbind(){
// this.$off('atguigu') //只是用解绑一个自定义事件
// this.$off(['atguigu','demo'])
this.$off() //所有的事件都解绑
}
},
};
</script>