vue学习,五生命周期 的钩子函数

生命周期的钩子函数 主要有以下几种

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
activated
deactivated
beforeDestroy
destroyed
errorCaptured     * 不经常用我们这里不介绍

具体介绍 看代码

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width ,initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>

<div >
    <!--用子-->
    <App></App>
</div>

<script>
    // 全局组件
    Vue.component('Vlife', {
        // 组件中的data一定是一个函数
        data() {
            return {
                msg: '生命周期'
            }
        },
        methods: {
            handlerClick() {
                this.msg = '晓强'
            }
        },
        template: `<div>
                    <button @click="handlerClick">改变(beforeUpdate和Update)</button>
                    {{msg}}
                  </div>`,
        beforeCreate() {
            console.log('组件创建之前', this.$data)
        },
        created() {
            // 非常重要的事情,在此时发送ajax 请求后端的数据 然后赋值给msg
            console.log('组件创建完成', this.$data)
        },
        beforeMount() {
            // 在挂载开始之前被调用  实际是还没有被加载出来
            console.log('DOM在挂载之前', document.getElementById('app'))
        },
        mounted() {
            // DOM挂载完成 也可以这发送 ajax 网页图片处
            console.log('DOM挂载完成', document.getElementById('app'))
        },
        beforeUpdate() {
            // 改变当前的元素 有个按钮在Vlife里[获取原始的DOM]
            console.log('更新之前的DOM', document.getElementById('app').innerHTML)
        },
        updated() {
            // 获取最新的DOM
            console.log('更新完成之后的DOM', document.getElementById('app').innerHTML)
        },
        beforeDestroy() {
            // 销毁之前 在父组件中
            console.log('销毁之前')
        },
        destroyed() {
            // 销毁之后
            console.log('销毁之后')
        },
        activated() {
            // 激活           这两个方法要配合 keep-alive 保持活跃状态相当于把组件放在一个缓存中
            // 可以用在一个页面退回到另一个页面 还保持原来的状态
            console.log('组件被激活了')
        },
        deactivated() {
            // 停用           这两个方法要配合 keep-alive 保持活跃状态相当于把组件放在一个缓存中
            console.log('组件被停用了')

        },
    });


    //     生子
    const App = {
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            clickHandler() {
                this.isShow = !this.isShow
            }
        },
        template: `<div>
                    <!--<Vlife v-if="isShow"></Vlife>-->
                    <keep-alive><Vlife v-if="isShow"></Vlife></keep-alive>
                    <button @click="clickHandler">改变组件的生死(beforeDestroy)</button>
                    </div>`
    };

    let app = new Vue({
        el: '#app',
        data: {},
        template: ``,
        // 挂子
        components: {
            App
        }
    })
</script>
</body>
</html>