vue 生命周期

发布时间 2023-08-02 15:12:25作者: 繁星学习中心

vue的生命周期就是vue从创建到销毁的过程

主要分为八个部分

  • beforeCreate(初始化界面前)
  • created(初始化界面后)
  • beforeMount(渲染dom前)
  • mounted(渲染dom后)
  • beforeUpdate(更新数据前)
  • updated(更新数据后)
  • beforeDestroy(卸载组件前)
  • destroyed(卸载组件后)

 

每个部分都做了什么?来看看的生命周期流程图:

 代码实现

 1 <script>
 2 export default {  
 3   // 在实例初始化之后,数据观测和事件配置之前被调用
 4   beforeCreate(){
 5     console.log('beforeCreate----创建前');
 6   },
 7   // 实例已经创建完成之后被调用
 8   created(){
 9     console.log('created----创建之后');
10   },
11   // 页面准备挂载时候被调用,此时相关的渲染函数首次被调用
12   beforeMount(){
13     console.log('beforeMount----挂载开始');
14   },
15   // 挂在完成,也就是模板中的HTML渲染到HTML页面中,此时一般可以做一些ajax操作,mounted只会执行一次。
16   mounted(){
17     console.log('mounted----挂载完成');
18   },
19   // 数据更新之前被调用
20   beforeUpdate(){
21     console.log('beforeUpdate----更新之前被调用');
22   },
23   //数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子
24   updated(){
25     console.log('updated----更新后');
26   },
27   // 我们将要销毁整个页面或实例时调用
28   beforeDestroy(){
29     console.log('beforeDestroy----销毁前');
30   },
31   // 我们的整个页面或实例被销毁之后调用
32   destroyed(){
33     console.log('destroyed----销毁后');
34   },
35   // 被 keep-alive 缓存的组件激活时调用
36   activated(){
37     console.log('activated');
38   },
39   //  deactivated配合keep-alive来使用
40   //  使用了keep-alive就不会调用beforeDestory和destoryed钩子了
41   //  因为组件没有被销毁,而是被缓存起来了
42   //  所以deactivated钩子可以看做是beforeDestory和destoryed的替代
43   deactivated(){
44     console.log('deactivated');
45   }
46 }
47 </script>