Vue 组件自定义事件_解绑
解绑单个自定义事件:this.$off('xxx')
解绑多个自定义事件:this.$off(['xxx','xxx'])
解绑所有自定义事件:this.$off()
通过销毁当前组件的实例,导致当前组件实例的自定义事件全部不奏效:this.$destroy
实例
App.vue
<template>
<div class="app">
<h2>{{msg}}</h2>
<my-student @hellodemo="getStudentName" @demo="m1"/>
</div>
</template>
<script>
import MyStudent from "@/components/MyStudent";
export default {
name: 'App',
components: {MyStudent},
data() {
return {
msg: '你好'
}
},
methods: {
getStudentName(name) {
console.log('App 收到学生名称:', name)
},
m1(){
console.log('deme 事件被触发')
}
},
}
</script>
<style scoped>
.app {
background-color: #979696;
padding: 5px;
}
</style>
MyStudent.vue
<template>
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生名给 App</button>
<button @click="unbind">解绑 hellodemo 事件</button>
</div>
</template>
<script>
export default {
name: "MyStudent",
data(){
return {
name:'张三',
age:19
}
},
methods:{
sendStudentName(){
this.$emit('hellodemo',this.name)
this.$emit('demo')
},
unbind(){
// 解绑单个自定义事件
this.$off('hellodemo')
// 解绑多个自定义事件
this.$off(['hellodemo','demo'])
// 解绑所有自定义事件
// this.$off()
}
}
}
</script>
<style scoped>
.student{
background-color: #b2dece;
padding: 5px;
margin-top: 30px;
}
</style>