浅谈一下 Vue 生命周期的一些相关面试点:
- 生命周期有哪些
( 系统自带 ):
beforeCreate created beforeMount mounted beforeUpdate updated beforeDestroy destroyed
( 加入了keep-alive组件 )会多两个生命周期:
activated deactivated
- 各生命周期的作用
生命周期的八个阶段 : 创建前/后,载入前/后,更新前/后,销毁前/后
beforeCreate :实例被创建前 created :实例被创建后,$data 已存在 beforeMount :实例挂载前 mounted :实例挂载后,$el;$data 已存在 beforeUpdate :数据对象 data 更新时 updated :新的数据对象 data 渲染后 beforeDestroy :实例销毁前 destroyed :实例销毁后
activated :在 keep-alive 组件激活时调用 deactivated :在 keep-alive 组件停用时调用
- 进入到页面或者组件,会执行哪些生命周期与其顺序
beforeCreate
created
beforeMount
mounted
- 在哪个阶段有 $el ,在哪个阶段有 $data
beforeCreate(undefined,undefined)
created(undefined,$data)
beforeMount(undefined,$data)
mounted($el,$data)
- 如果加入了keep-alive,第一次进入组件会执行哪些生命
beforeCreate
created
beforeMount
mounted
activated
- 如果加入了keep-alive,第二次或者第N次进入组件会执行哪些生命周期
activated
当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们;所以后面再调用只执行activated生命周期
keep-alive :
是Vue的内置组件,在组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性。
原理:
在 created 函数调用时将需要缓存的 VNode 虚拟DOM节点保存在 this.cache 中,
在 render(页面渲染) 时,如果 VNode 的 name 符合缓存条件(可以用 include 以及 exclude 控制),
则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染。
使用 keep-alive 会将数据保留在内存中,如果要在每次进入页面的时候获取最新的数据,
需要在 activated 阶段获取数据,承担原来 created 钩子函数中获取数据的任务。
注意:
只有组件被 keep-alive 包裹时,这两个生命周期函数才会被调用,如果作为正常组件使用,是不会被调用的,
以及在 2.1.0 版本之后,使用 exclude 排除之后,就算被包裹在 keep-alive 中,这两个钩子函数依然不会被调用!
另外,在服务端渲染时,此钩子函数也不会被调用。
keep-alive内置组件的Props
- include - 字符串或正则表达式 :只有名称匹配的组件会被缓存。
- exclude - 字符串或正则表达式 :任何名称匹配的组件都不会被缓存。
- max - 数字 :最多可以缓存多少组件实例。
相关资料:
https://blog.csdn.net/fu983531588/article/details/90321827
https://zhuanlan.zhihu.com/p/96740001
https://baijiahao.baidu.com/s?id=1683494653812131236&wfr=spider&for=pc
https://www.imooc.com/article/302879
- 生命周期的执行原理
index.html >------ <script type=" text/ javascript" scr="vue.js"></script> <script type=" text/ javascript"> new Vue({ el:" #app" , data{str: '123 '}, beforeCreate(){}, created(){}, beforeMount(){}, mounted(){} }) </script> -- index.html中按任何顺序调用生命周期函数都不会影响执行顺序,因为vue.js中控制了执行顺序 -- vue.js >----- class Vue{ constructor( options ){ options.beforeCreate.bind(this)() this.$data = options.data; options.created.bind(this)() options.beforeMount.bind(this)() this.$el = document.querySelector(options.el); options.mounted.bind(this)() }} -- vue.js 中 还控制了在哪个阶段有 $el ,在哪个阶段有 $data --