VUE 生命周期函数

export default {
     name: 'HomeBasic',
     data() {
         return {
             text: 'home-basic-container'
         };
     },
     methods: {
         handleClick() {
             this.change();
         },
         change() {
             // console.log('self change');
          this.text = 'xxx';
         },
       destroyAll() {
          this.$destroy();
       }
     },
    watch: {
       text() {
          console.log('text change');
       }
    },
    beforeCreate() {
       /*
          实例初始化后,创建完成之前被调用
       */
       console.log('1. beforeCreate');
    },
    created() {
       /*
          实例创建完成后被立即调用,这个时候还没有开始挂载 不能访问 $el
       */
       // this.text = 'cbd'; // 更改状态有效
       // console.log(this.$el); // undefined
       console.log('2. created');
    },
    beforeMount() {
       /*
          挂载开始之前调用,即将开始挂载
       */
       console.log('3. beforeMount');
    },
    mounted() {
       /*
          实例挂载之后调用,但是并不是所有子组件也都一起挂载完成
       */
       this.$nextTick(function () {
          console.log('4. mounted nextTick');
       });
       console.log('5. mounted');
    },
    beforeUpdate() {
       /*
          数据更新完成前调用,发生在虚拟DOM重新渲染和打补丁前,在这里进一步的更改状态,不会触发重新渲染
       */
       console.log('6. beforeUpdate');
       if (this.text) {
          this.text = 'beforeUpdate';
       }
    },
    updated() {
       /*
          更改数据重新渲染虚拟DOM后调用
       */
       this.$nextTick(function () {
          console.log('7. updated nextTick');
       });
       console.log('8. updated');
    },
    beforeDestroy() {
       /*
          实例销毁之前调用,在这一步,实例仍然可用
       */
       console.log('9. beforeDestroy');
    },
    destroyed() {
       console.log('10. destroyed');
    }
 };

 /*
    1. beforeCreate
    2. created
    3. beforeMount
    5. mounted // this.$nextTick(fn) 会在 所有子组件挂在后执行
    4. mounted nextTick

    // 手动触发状态更改
    text change
    6. beforeUpdate // 在 beforeUpdate 中可以更改状态,不会触发重复渲染
    text change
    6. beforeUpdate // 如下可以看到 只是重新走了一遍 update 不会无限循环下去
    8. updated(2)
    7. updated nextTick(2)
 */

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。