一道基础Vue生命周期的面试题


根据Vue的生命周期说出console打印出来的值

export default {
  data() {
    num1: 1,
    num2: 2,
  },
  computed: {
    sum() {
      return this.num1 + this.num2;
    }
  },
  beforeCreate() {
    console.log("beforeCreated", this.sum);  // undefined    (页面载入触发)
  },
  created() {
    console.log("created", this.sum);  // 3     (页面载入触发)
  },
  beforeMount() {
    console.log("beforeMount", this.sum); // 3     (页面载入触发)
  },
  mounted() {
    console.log("mounted", this.sum); // 3     (页面载入触发)
  },
  beforeUpdate() {
    console.log("beforeUpdate", this.sum); // 3     (有数据更新时才会触发)
  },
  updated() {
    console.log("updated", this.sum); // 3     (有数据更新时才会触发)
  },
  beforeDestroy() {
    console.log("beforeDestroy", this.sum); // 3     (离开组件时才会触发)
  },
  destroyed() {
    console.log("destroyed", this.sum); // 3    (离开组件时才会触发)
  }
}

拓展

  • 父子组件生命周期如何执行
    • 父beforeCreate -> 父created -> 父beforeMount ->
    • 子beforeCreate -> 子created -> 子beforeMount -> 子mounted ->
    • 父mounted ->
    • 父beforeUpdate -> 子beforeUpdate -> 子updated -> 父updated ->
    • 父beforeDestroy-> 子beforeDestroy -> 子destroyed -> 父destroyed

文章作者: Damao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Damao !
  目录