vue实例有一个完整的生命周期,也就是vue实例从 创建前(beforeCreate)、创建后(created)、载入前(beforeMount)、载入后(mounted)、更新前(beforeUptate)、更新后(updated)、销毁前(beforeDestroy)、销毁后(destroyed)一系列过程,我们称之为vue的生命周期。
 
 通俗来讲就是vue实例从创建到销毁的过程就是生命周期。
 
 我们一般把vue的生命周期分为三个阶段:初始化、运行中、销毁。
 
 
 
 (1) beforeCreate:
 
 beforeCreate() { 
  console.log('beforeCreate--$el:', this.$el); 
  console.log('beforeCreate--$data:', this.$data);
  console.log('beforeCreate--res:', this.res); 
}
 
 
 
 从打印的结果来看我们知道:
 
 beforeCreate --- 在vue实例完全被创建出来之前(意思就是说vue实例还没有被完全创建出来)被调用,此时数据还没有被初始化,所以无法访问数据,
 
 
 
  (2) created:
 
 created() {
  console.log('created--$el:', this.$el); 
  console.log('created--$data:', this.$data); 
  console.log('created--res:', this.res); 
}
 
  
 
 
 从打印的结果来看我们知道:
 
 created --- 在vue实例创建完成后被调用,这个过程已完成了数据的初始化,可以被访问得到;这个过程可以修改数据,这也是渲染之前修改数据的机会。
 
 
 
 (3) beforeMount:
 
 beforeMount() {
  console.log('beforeMount--$el:', this.$el);
  console.log('beforeMount--$data:', this.$data);
  console.log('beforeMount--res:', this.res);
},
 
 
 
 beforeMount --- 这个过程是在模版挂载之前被调用,render函数也是首次被调用,此时完成了虚拟Dom的构建,但并未被渲染,这也是最后一次修改数据的机会。
 
 
 
 (4) mounted:
 
 mounted() {
  console.log('mounted--$el:', this.$el);
  console.log('mounted--$data:', this.$data);
  console.log('mounted--res:', this.res);
},
 
 
 
 mounted --- 这个过程在模版挂载之后被调用,完成渲染,所以我们可以操作Dom。
 
 
 
 (5) beforeUpdate:
 
 这个钩子函数是在重新渲染之前(更新前)调用,这个过程是不能更改数据的;如果在调用这个钩子函数之前数据没有改变的话,是无任何变化的;当数据发生改变之后,这个过程再次调用render函数,它会重新构建虚拟Dom,然后与上次生成的虚拟Dom树利用diff算法进行对比找出差异,准备下次的重新渲染。
 
 
 
 (6) updated:
 
 这个过程在重新渲染之后(更新后调用),已渲染完成
 
 
 
 (7) beforeDestroy:
 
 这个过程是vue实例销毁之前被调用,在这个过程中我们可以做一些事情,比如 清除计时器或事件等等。
 
 
 
 (8) destroyed:
 
 vue实例销毁后调用,并且vue实例中所有的东西都会解绑,所有的事件监听器都会被移除,所有的子实例也会被销毁。