Vue2 生命周期 lifecycle

图片出处 : 我的github博客https://github.com/songxtianx/Front-End-Blog

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue"></script>
</head>
<body><div id="app">{{msg}}</div>
<script>
var app = new Vue({
  el: '#app',
  data: {
    msg: 'created1',
  },
  beforeCreate() {
    console.log("beforeCreate ===", this.$el, this.msg, "loading事件");
  },
  created() {
    console.log("created      ===", this.$el, this.msg, "初始化,实现函数自执行");
  },
  beforeMount() {
    this.msg = "mounted2";
    console.log("beforeMount  ===", this.$el,  this.msg, "  创建vm.$el并将“el”替换为它。");
  },
  mounted() {
    setTimeout(() => {
      app.$destroy()
    }, 1000);
    console.log("mounted         ===", this.$el, this.msg, " 发起后端请求,拿回数据,配合路由钩子");
    this.msg = "updated3";
  },
  beforeUpdate() {
    // this.msg = "updated3";
   console.log("beforeUpdate ===", this.$el, this.msg, " 虚拟DOM重呈现和修补程序");
  },
  updated() {
    // this.msg = "updated3";
    console.log("updated      ===", this.$el, this.msg, " 更新");
  },
  beforeDestroy:function(){
    this.msg = "destroyed4";
    console.log("beforeDestroy===", this.$el, this.msg, " 确定要销毁组件吗?")
  },
  destroyed:function(){
        console.log("destroyed    ===", this.$el, this.msg, " 观察器、子组件和事件监听器已拆卸。")
  }
})
</script>
</body>
</html>

每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。

比如 created 钩子可以用来在一个实例被创建之后执行代码:


也有一些其它的钩子,在实例生命周期的不同阶段被调用,如 mounted、updated 和 destroyed。生命周期钩子的 this 上下文指向调用它的 Vue 实例。

博主Github地址

猜你喜欢

转载自www.cnblogs.com/cnxusong/p/9712371.html