Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【vue】 谈谈Vue的生命周期钩子的理解 #61

Open
yayxs opened this issue Apr 7, 2021 · 0 comments
Open

【vue】 谈谈Vue的生命周期钩子的理解 #61

yayxs opened this issue Apr 7, 2021 · 0 comments

Comments

@yayxs
Copy link
Owner

yayxs commented Apr 7, 2021

首先要了解声明周期的合并策略,

let res = (是否有childVal,判断组件的选项中是否有对应名字声明周期钩子)?如果有判断是否有parentVal?如果有将二者合并一个数据:如果没有判断childVal 是不是一个数组?如果childVal是一个数组直接返回:如果不是作为数组的元素然后返回:如果没有childVal直接返回parentVal
function mergeHook(
  parentVal: ?Array<Function>,
  childVal: ?Function | ?Array<Function>
): ?Array<Function> {
  const res = childVal
    ? parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
      ? childVal
      : [childVal]
    : parentVal
  return res ? dedupeHooks(res) : res
}
export const LIFECYCLE_HOOKS = [
  'beforeCreate',
  'created',
  'beforeMount',
  'mounted',
  'beforeUpdate',
  'updated',
  'beforeDestroy',
  'destroyed',
  'activated',
  'deactivated',
  'errorCaptured',
  'serverPrefetch',
]

vue 生命周期进阶

基本流程

  • new vue 创建实例
  • 初始化事件 生命周期
  • beforeCreate
  • 初始化 注入校验
  • created
  • 是否指定 el
    • 否: 调用 vm.$mount(el)
    • 是:是否指定 template
      • 否 将 el 外部的 html 作为 template 编译
      • 是 将 template 编译到 render
  • beforeMount
  • 创建 vm.$el 并用其替换 el
  • mounted
  • 挂载完毕
  • 当 data 修改的时候:
    • beforeUpdate
    • updated
  • 调用 vm.$destroy()
  • beforeDestroy
  • 解除绑定 销毁子组件 事件监听
  • 销毁完毕
  • destroyed

加载渲染的过程

父组件挂载完毕肯定是等里面的子组件都挂载完毕后才算父组件挂载完毕了,所以父组件的 mounted 在最后。

子组件更新过程

子组件更新过程(子组件更新影响到父组件的情况):父beforeUpdate -> 子beforeUpdate->子updated -> 父updted
子组件更新过程(子组件更新不影响父组件的情况):子beforeUpdate -> 子updated

父组件更新过程

20200421221422

eactivated 函数的触发时间是在视图更新时触发。因为当视图更新时才能知道 keep-alive 组件被停用了。

父组件更新过程(父组件影响子组件的情况):父beforeUpdate -> 子beforeUpdate->子updated -> 父updted
父组件更新过程(父组件不影响子组件的情况):父beforeUpdate -> 父updated

销毁过程

父 beforeDestroy->子 beforeDestroy->子 destroyed->父 destroyed

小补充

deactivated keep-alive 组件停用时调用。
activated keep-alive 组件激活时调用。

总结

Vue 父子组件生命周期钩子的执行顺序遵循:从外到内,然后再从内到外,不管嵌套几层深,也遵循这个规律

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant