03_04.组件销毁生命周期函数

<!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>
</head>
<body>
    <main id="app">
        <app-header v-if="headerIsShow"></app-header>
        <button @click="changeHeader">显示隐藏header</button>
    </main>

    <script src="vue.js"></script>
    <script>
        Vue.component('app-header', {
            template: `<header>{{ tit }}</header>`,
            data: function() {
                return {
                    tit: '标题',
                    timer: null
                };
            },

            // 数据可以使用了
            created: function() {
                this.timer = setInterval(function() {
                    console.log('你好!');
                }, 1000);
            },

            // 组件销毁前执行
            beforeDestroy: function() {
                console.log('beforeDestory');
                console.log(document.querySelector('header'));
            },

            // !!重点!!
            // 组件销毁后执行, 同时数据绑定也失效了
            destroyed: function() {
                clearInterval(this.timer);
                console.log('destoryed');
                console.log(document.querySelector('header'));
            }
        });

        var vm = new Vue({
            el: '#app',
            data: {
                headerIsShow: true
            },
            methods: {
                changeHeader: function() {
                    this.headerIsShow = !this.headerIsShow;
                }
            }
        });
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容