组件生命周期的组件钩子之外部内部销毁

本文深入探讨Vue组件的生命周期,特别是销毁阶段的beforeDestroy和destroyed钩子。通过两种不同的销毁方式,即通过开关销毁和使用$destroy()方法,详细解析了它们在DOM结构处理上的差异。文章提供了具体的代码示例,帮助读者理解如何在组件销毁时进行资源清理,如清除定时器和DOM操作。

组件生命周期的组件钩子之外部/内部销毁

第三步的销毁:beforedestroy / destroyed

销毁方式:最大区别就是第二种无法销毁dom结构

1、通过开关销毁(flag,可以销毁该组件的dom结构)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click="flag=!flag">切换</button>
        <congbo v-if="flag"></congbo>
    </div>

    <template id="all">
        <div>
            测试文本
        </div>
    </template>
</body>
    <script>
        Vue.component('congbo',{
            template:'#all',
            mounted(){
              this.time=setInterval(function(){
                    console.log(1999)
                },1000)
            },
            destroyed(){
                //destroyed这里处理  相关dom的操作、定时器关闭、第三方实例的删除,主要用来处理善后工作
                clearInterval(this.time)
                console.log('destroyed')
            }
        })
        new Vue({
            el:'#app',
            data:{
                flag:true
            }
        })
    </script>
</html>

2、通过$destroy()销毁(这种没有销毁掉dom结构,需要相关dom操作再次销毁)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
    <div id="app">
        <congbo></congbo>
    </div>

    <template id="all">
        <div class="box">
            <button @click="clear">销毁</button>
                测试文本
            </div>
    </template>
</body>
    <script>
        Vue.component('congbo',{
            template:'#all',
            methods: {
                clear(){
                    console.log(this)
                    this.$destroy()
                }
            },
            mounted(){
              this.time=setInterval(function(){
                    console.log(1999)
                },1000)
            },
            destroyed(){
                clearInterval(this.time)
                console.log('destroyed')
                //操作dom销毁dom结构
                document.querySelector('.box').remove()
            }
        })
        new Vue({
            el:'#app',
            data:{
                flag:true
            }
        })
    </script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值