Vue的八大生命周期钩子函数

 /* Vue实例化对象创建之前 */

beforeCreate:Vue实例化对象创建之前,获取不到data里面的数据的

created:Vue实例化对象创建之后,可以获取data里面的数据,不可以获取到dom包括根节点

    <div id="app">
        <h1>{{msg}}</h1>
    </div>
    <script src="./vue.min.js"></script>
    <script>
        new Vue({
            el: "#app",
            data: {
                msg: "前端工作"
            },
            // 最先执行的函数
            beforeCreate: function () {
                console.log("vue实例化对象创建之前");
                // console.log(this.msg);
            },
            created() {
                console.log("vue实例化对象创建之后");
                console.log(this.msg);
                console.log(document.querySelector("#app"));
                // created 在生命周期里面不可能获取节点
                console.log(this.$el);
                // ⭐一般用来获取接口数据,速度更快,因为这个时候已经获取到data的数据了
                setTimeout(() => {
                    this.msg = "从接口获取的数据"
                }, 100)
            },
            beforeMount() {
                // beforeMount 在生命周期里面可获取节点,但是不能显示出data数据
                console.log('beforeMount', this.$el);
            },
             mounted() {
              // ⭐操作元素节点的时候,写在mounted
                console.log('mounted', this.$el);
            }

        })
    </script>

/* Vue的dom挂载之前 */

beforeMount:dom挂载之前可以获取到根节点,还没有把data中的数据渲染到dom节点上

mounted:已经把data中的数据渲染到了dom节点上

 beforeMount() {
                // beforeMount 在生命周期里面可获取节点,但是不能显示出data数据
                console.log('beforeMount', this.$el);
            },
            mounted() {
                // 操作元素节点的时候,写在mounted
                console.log('mounted', this.$el);
                this.id = setInterval(() => {
                    this.num++;
                    console.log(this.num);
                }, 1000)
            },

/* 当把Vue实例中的data中的值改变了会触发beforeUpdate和updated */

beforeUpdate在生命周期里面可获取节点,但是不能显示出data数据

updated操作元素节点的时候,写在mounted

   // 在data更新之前执行
            beforeUpdate() {
                console.log('beforeUpdate', this.msg, this.$el);
            },
            updated() {
                console.log('beforeUpdate', this.msg, this.$el);
            },

 /* Vue组件销毁前 */

beforeDestroy:在调用$destroy()方法的时候 会执行下面的两个钩子函数

destroyed:/* ★beforeDestroy和destroyed的一个使用场景是在销毁定时器节约内存的时候都可以使用 */

 beforeDestroy() {
                clearInterval(this.id)
                console.log('beforeDistory', this.msg, this.$el);
            },
            destroyed() {
                // clearInterval(this.id)
                console.log('destory', this.msg, this.$el);
            },
            methods: {
                changeFn() {
                    this.msg = "111111111111111111"
                },
                destroyFn() {
                    this.$destroy()
                }
            }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值