Vue生命周期执行测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="root">
        <div>{{fullName}}</div>
        <button @click="change">change firstName</button>
    </div>


    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
    <script>
        new Vue({
            el: '#root',
            data: {
                firstName: 'Rick',
                lastName: 'Xu'
            },
            computed: {
                /*
                    使用的时候才会执行: 1. 页面绑定, 2 代码调用
                    不要再computed,对data属性的值进行修改
                */
                fullName: function() {
                    let fullName = this.firstName + ' ' + this.lastName
                    console.log('-  computed ', fullName)
                    return fullName
                }
            },
            watch: {
                /*
                    整个生命周期,只会出发一次监控
                */
                firstName: function(val, old) {
                    console.log('-  watch ', old, ' => ', val)
                }
            },
            created() {
                /*
                    // 还未完成页面渲染
                    ajax请求放在created中,比在mounted好

                    1. 会调用computed
                    2. 因为mounted也对「firstName」进行了修改,「watch」mounted后被调用一次。created不调用
                */

                // console.log(this.fullName) // Rick.Xu 手动调用
                this.firstName = 'Jim'
                console.log('1. created')
                // 1. 页面绑定了computed属性,会调用一次

            },
            mounted() {
                /*
                    完成页面渲染
                    会调用watch和computed方法
                    操作dom,jquery事件绑定在这里处理
                */
                this.firstName = 'Ashley'
                console.log('2. mounted')
            },
            updated() {
                console.log('3. updated')
            },
            methods: {
                change: function() {
                    /*
                        先执行watch,再computed
                    */
                    this.firstName = 'Lucy'
                    console.log('4. change')
                }
            }
        })

    </script>
</body>
</html>

http://xhope.top/wp-content/uploads/2020/11/qq.png