【vue】Vue实例的生命周期
source link: https://segmentfault.com/a/1190000040717177
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Vue实例的生命周期
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforDestroy
- destroyed
其他lifecycle_hook
keep-alive配合使用的
activated
和deactivated
捕获错误的errorCaptured
处理ssr的serverPrefetch
各阶段生命周期函数说明
1 beforeCreate created
这两个hook是在模板编译之前,初始化阶段执行
源码
在调用beforeCreate之前
- 初始化生命周期
- 初始化事件
- 初始化render
在调用created之前
- 初始化注入
- 初始化
状态
- 初始化provide
initState
function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } }
初始化状态
- initProps
- initMethods
- initData
- initComputed
- initWatch
initState的调用在beforeCreate与created
之间
,所以
beforeCreate获取不到vm上的data与methods
created能获取到
2 beforeMount mounted
beforeMount在模板编译后,挂载前,mounted在挂载之后
调用beforeMount之前
- 判断el与template
- 调用
$mount
函数 - 模板编译完成
Vue.prototype.$mount源码
调用mounted之前
- 将编译好的模板挂载到页面
源码
beforeMount上能获取模板信息,但是页面未显示
mounted页面挂载完成
到mounted为止,从无到有,创建阶段完成
在运行阶段未发生销毁,不会再调用以上hooks
3 beforeUpdate updated
运行阶段的hooks
beforeUpdate在数据改变后页面渲染前,updated在新数据渲染到页面后
在上面的源码中可以看到,watcher侦测到数据变化时就会调用beforeUpdate
在数据更新完成后会调用updated
4 beforeDestroy destroyed
在调用$destroy
时会调用这两个hook
在beforeDestoy之后开始销毁
- 从父级拆除
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK