原生事件跟自定义事件
问题描述:
我使用
this.$destroy()
去销毁当前的组件实例对象
我同时绑定了原生事件 跟自定义事件
我预期的是,销毁之后,原生的事件还能被调用,(控制台有输出),只是响应式丢了
页面真实的展示是:销毁之后,不管是原生的还是自定义的,都挂了,无法再被点击调用
我想跟老师证实的是,是不是销毁组件实例对象之后,不论什么原生不原生,通通会挂掉
代码如下
<template>
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<h2>当前求和为:{{ number }}</h2>
<button @click="add">点我number++</button>
<button @click="sendStudentName">把学生名给App</button>
<button @click="unBind">解绑atguigu事件</button>
<button @click="death">销毁当前Student组件的实例对象(vc)</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: 'Tom',
sex: '男',
number: 0,
};
},
methods: {
add() {
console.log('add回调被调用了');
this.number++;
},
sendStudentName() {
// 触发 student 组件实例身上的 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组件的实例对象(vc)
},
},
};
</script>
<style lang="less">
.student {
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
正在回答 回答被采纳积分+1
同学你好,销毁组件实例后,页面已经渲染的元素节点,所有渲染完成的数据不会销毁,只是没有Vue 的管理了(无无响应式);会移除watch监听,子组件,自定义事件等,原生的事件回调移除不了。
同学的代码无法测试,可以用下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | <template> <div id= "root" > <h2>当前的n 值为{{n}}</h2> <button @click= "add" > 点我n++</button> <button @click= "on" > 添加自定义事件</button> <button @click= "off" > 卸载自定义事件</button> <button @click= "bey" > 点我销毁</button> </div> </template> <script> export default { name: 'Student' , data() { return { n: 1, } }, methods: { add() { console.log( "调用了 add " ) this .n++; this .$emit( 'test' ) }, bey() { console.log( "销毁完成" ); this .$destroy(); }, on() { this .$on( 'test' , () => { console.log( "添加上了自定义事件" ); }) console.log( '调用了on' ) }, off() { this .$off(); } }, watch: { n() { console.log( "监听器监听到了 n 发生了变化 " ); } }, mounted() { console.log( "mounted" ); }, beforeUpdate() { console.log( "beforeUpdate:" , this .n); }, updated() { console.log( "updated:" , this .n); this .$emit( 'test' ) } } </script> |
销毁后点击‘add’按钮,会输出‘add’,但是n值不会变化
自己测试下,祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧