Vue生命周期

2019-04-09  本文已影响0人  我的木

Vue生命周期就是Vue实例从创建到销毁的整个过程,分为八个阶段,有八个钩子。

官方文档中给了一个图,嗯……看不明白,也不知道每个阶段到底都干了啥


lifecycle

看图不如直接上代码,我在每一个钩子函数中将el、data和data里的属性message都alert出来,不用console打印而用alert是因为这样可以看到页面什么时候被渲染出来。

//HelloWorld.vue
<template>
  <div class="hello">
    <input v-model="message"/>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        message: 'hello'
      }
    },
    beforeCreate: function () {
      console.log('beforeCreate--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    created: function () {
      console.log('created--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    beforeMount: function () {
      console.log('beforeMount--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    mounted: function () {
      console.log('mounted--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    beforeUpdate: function () {
      console.log('beforeUpdate--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    updated: function () {
      console.log('updated--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    beforeDestroy: function () {
      console.log('beforeDestroy--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    },
    destroyed: function () {
      console.log('destroyed--------------:');
      alert('el:' + this.$el + '  ' + 'data:' + this.$data + '  ' + 'message:' + this.message);
    }
  };
</script>

保存后浏览器打开localhost:8080。
首先是beforeCreated,此时el、data都是undefined,页面上还什么也没有。


beforeCreate.png

created时data已被初始化,但el还是undefined,页面还没有渲染出来


created.png beforeMount.png

mounted时el初始化,页面渲染出


mounted.png mounted.png

只要更改页面上的数据,就会触发beforeUpdate,把输入框里的hello改为hell,可以看到此时的alert出message已经改变,但页面上还没有变,在updated时页面数据更新


beforeUpdate.png updated.png updated.png

从上边的结果来看created和beforeMounted都是data已初始化,el还未初始化,但是我在网上看其他人的结果却不一样,在其他文章看到说“beforeMount就完成了 el 和 data 初始化 ,此时el还是 {{message}},应用了 Virtual DOM(虚拟Dom)技术,先把坑占住了,到后面mounted挂载的时候再把值渲染进去”,下边是他人打印的结果。


参考文章:https://segmentfault.com/a/1190000008010666

为什么我打印的没有虚拟DOM?这先作为一个遗留问题。

上一篇 下一篇

猜你喜欢

热点阅读