Vue

🌸 您好,欢迎您的阅读,等君久矣,愿与君畅谈.
🔭 § 始于颜值 § 陷于才华 § 忠于人品 §
📫 希望我们可以进一步交流,共同学习,共同探索未知的技术世界 稀土掘金 OR GitHub.


# Vue 生命周期的理解

每个 Vue 实例在创建时都会经过一系列的初始化过程, vue 的生命周期钩子,就是说在达到某一阶段或条件时去触发的函数,目的就是为了完成一些动作或者事件

  • create阶段 :vue 实例被创建
    beforeCreate : 最初调用触发,创建前,此时 data 和 methods 中的数据都还没有初始化,data 和 events 都不能用
    created : 创建完毕,data 中有值,未挂载,data 和 events 已经初始化好,data 已经具有响应式;在这里可以发送请求
  • mount阶段 : vue 实例被挂载到真实 DOM 节点
    beforeMount :在模版编译之后,渲染之前触发,可以发起服务端请求,去数据,ssr 中不可用,基本用不上这个 hook
    mounted : 在渲染之后触发,此时可以操作 DOM,并能访问组件中的 DOM 以及 $ref,SSR 中不可用
  • update阶段 :当 vue 实例里面的 data 数据变化时,触发组件的重新渲染
    beforeUpdate : 更新前,在数据变化后,模版改变前触发,切勿使用它监听数据变化
    updated :更新后,在数据改变后,模版改变后触发,常用于重渲染案后的打点,性能检测或触发 vue 组件中非 vue 组件的更新
  • destroy阶段 :vue 实例被销毁
    beforeDestroy :实例被销毁前,组件卸载前触发,此时可以手动销毁一些方法,可以在此时清理事件、计时器或者取消订阅操作
    destroyed : 卸载完毕后触发,销毁后,可以做最后的打点或事件触发操作
# 组件生命周期

生命周期(父子组件) 父组件 beforeCreate --> 父组件 created --> 父组件 beforeMount --> 子组件 beforeCreate --> 子组件 created --> 子组件 beforeMount --> 子组件 mounted --> 父组件 mounted --> 父组件 beforeUpdate --> 子组件 beforeDestroy–> 子组件 destroyed --> 父组件 updated

加载渲染过程 父 beforeCreate-> 父 created-> 父 beforeMount-> 子 beforeCreate-> 子 created-> 子 beforeMount-> 子 mounted-> 父 mounted

挂载阶段 父 created-> 子 created-> 子 mounted-> 父 mounted

父组件更新阶段 父 beforeUpdate-> 父 updated

子组件更新阶段 父 beforeUpdate-> 子 beforeUpdate-> 子 updated-> 父 updated

销毁阶段 父 beforeDestroy-> 子 beforeDestroy-> 子 destroyed-> 父 destroyed

# Vue 的生命周期
  1. 生命周期:从创建到销毁的过程

  2. 生命周期函数内不能使用箭头函数,因为箭头函数没有 this , 生命周期中要进行应用

  3. var object = {
          message:"vue.js"
        }
        var vm = new Vue({
          el:"#app",
          data:object,
          beforeCreate: function() {
            console.log("beforeCreate");
          },
          created: function () {
            console.log("created");
          },
          beforeMount: function () {
            console.log("beforeMount");
          },
          mounted: function () {
            console.log("mounted");
          },
          beforeUpdate: function () {
            console.log("beforeUpdate");
          },
          updated: function () {
            console.log("updated");
          }
        });
        setTimeout(function (params) {
          vm.message = "chagege ......"
        },2000)

Vue
http://example.com/2020/02/27/6001_Vue/
作者
XGG
发布于
2020年2月27日
更新于
2023年6月3日
许可协议