系列文章只是基础内容的整理和记录,不具备深度。

生命周期方法

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • activated
  • deactivated
  • beforeDestroy
  • destroyed

https://cn.vuejs.org/images/lifecycle.png

beforeCreate 和 created

在 created 能够访问 data,并且能够触发 DOM render,而 beforeCreate 无法访问 this.data

网络请求应当放在 created 中。

代码示例:

  beforeCreate() {
    console.log('beforeCreate:' + this.title);
  },
  created() {
    console.log('created:' + this.title);
  },

效果:

3.jpg

beforeMount 和 mounted

生命周期发生在 DOM 装载前后,代码示例:

  beforeMount() {
    console.log('beforeMount' + document.body.innerHTML);
  },
  mounted() {
    console.log('mounted:' + document.body.innerHTML);
  },

效果:

1.jpg

2.jpg

beforeUpdate 和 updated

代码示例:

  beforeUpdate() {
    console.log("beforeUpdate: " + this.title);
  },
  updated() {
    console.log('updated: '+ this.title);
  }

没发现有 newValue 和 oldValue 的入参,API 地址:https://cn.vuejs.org/v2/api/#updated

效果:

两次取值一样

4.jpg

beforeDestroy 和 destroyed

如果通过 v-if 控制显示和隐藏组件,则销毁过程中会触发这两个生命周期,而在 beforeDestroy 和 destroyed 依旧能够获取 data 值。

代码示例:

  beforeDestroy() {
    console.log("beforeDestroy: " + this.title);
  },
  destroyed() {
    console.log('destroyed: '+ this.title);
  },

效果:

5.jpg

deactivated 和 activated

如果组件需要保活,会用到 <keep-alive> </keep-alive> 内置组件进行包裹,此时通过 v-if 控制显示和隐藏的组件,不会触发 destroyed 和 beforeDestroy 方法,而是触发 deactivatedactivated 方法。

代码示例:

// 父组件的 template
template:`<keep-alive> <Test v-if="show" /> </keep-alive>`,

// 子组件声明周期

  activated(){
    console.log('activated:组件激活状态')
  },
  deactivated(){
    console.log('activated:组件停用状态')
  }

效果:

6.jpg

完整代码示例

<script>
const Test = {
  template:`<div>
      <p>Test Component {{title}}</p> <button @click="title = title + 1">点击 </button>
  </div>`,
  data(){
    return {
      title:'title'
    }
  },
  beforeCreate() {
    console.log('beforeCreate:' + this.title);
  },
  created() {
    console.log('created:' + this.title);
  },
  beforeMount() {
    // console.log('beforeMount' + document.body.innerHTML);
  },
  mounted() {
    // console.log('mounted:' + document.body.innerHTML);
  },
  beforeUpdate() {
    console.log("beforeUpdate: " + this.title);
  },
  updated() {
    console.log('updated: '+ this.title);
  },
  
  beforeDestroy() {
    console.log("beforeDestroy: " + this.title);
  },
  destroyed() {
    console.log('destroyed: '+ this.title);
  },
  activated(){
    console.log('activated:组件激活状态')
  },
  deactivated(){
    console.log('activated:组件停用状态')
  }
}
new Vue({
  components:{Test},
  el: '#app',
  template:`<keep-alive> <Test v-if="show" /> </keep-alive>`,
  created(){
    setTimeout(()=>{
      this.show = false;
    },1000)
  },
  data(){
    return {
      show: true
    }
  }
})
</script>