Vue学习:组件自定义事件,解绑

使用 this.$off('自定义事件名称'):但是只能解绑一个事件

<template>
    <div class="student">
        <h1>{{msg}}</h1>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">传递学生名给APP</button>
        <button @click="unbind">解绑自定义mything</button>
    </div>
</template>

<script>
    
    export default {
        name: 'Student',
        data() {
            return {
                msg: '学生信息',
                name: "小李",
                sex: "女"
            };
        },
        methods: {
            sendStudentName(){
                //触发Student组件实例上的mything事件 传递的参数
                this.$emit('mything',this.name,4,5,67);
            },
            unbind(){
                this.$off('mything')
            }
        },
  

    };

解绑多个事件使用数组

unbindAll(){
                this.$off(['mything','mything1'])//解绑多个自定义事件
            }

或者: this.$off() 在实例上的所有自定义事件

 this.$off()

this.$destroy()生命周期钩子 销毁了当前student的组件实例 组件上事件监听没了,自定义事件也不奏效 原生DOM还在 这里需要对Vue的版本有需求

<template>
    <div class="student">
        <h1>{{msg}}</h1>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <h2>原生DOM+1:{{n}}</h2>
        <button @click="sendStudentName">传递学生名给APP+自定义mything1</button>
        <button @click="unbind">解绑自定义mything</button>
        <button @click="unbindAll">解绑所有事件</button>
        <button @click="death">销毁当前student组件实例对象(VC)</button>
        <button @click="n++">+1</button>
    </div>
</template>
  export default {
        name: 'Student',
        data() {
            return {
                msg: '学生信息',
                name: "小李",
                sex: "女",
                n:0
            };
        },
        methods: {
            sendStudentName(){
                //触发Student组件实例上的mything事件 传递的参数
                this.$emit('mything',this.name,4,5,67);
                this.$emit('mything1')
            },
            unbind(){
                this.$off('mything')//解绑一个自定义事件
            },
            unbindAll(){
                this.$off(['mything','mything1'])//解绑多个自定义事件
            },
            death(){
                this.$destroy()//销毁了当前student的组件实例
            }
    
        },
  

在vm上销毁 子组件都没了

new Vue({
    el: '#app',
    render: h => h(App),
    mounted(){
        setTimeout(() => {
            this.$destroy()
        }, 3000)
    },


});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值