vue源码中的一些方法

callHook函数的解析

使用方式

callHook(vm, 'beforeCreate')
callHook(vm, 'created')
复制代码

例子

let test = new Vue({
    data: {
        a: 1
    },
    created: function () {
        console.log("这里是Created");
    }
});
复制代码

具体代码

export function callHook (vm: Component, hook: string) {
  pushTarget() 
  const handlers = vm.$options[hook] //获取用户自定义的hook方法
  const info = `${hook} hook`
  if (handlers) { 
    for (let i = 0, j = handlers.length; i < j; i++) {
      invokeWithErrorHandling(handlers[i], vm, null, vm, info)
    }
  }
  if (vm._hasHookEvent) {
    vm.$emit('hook:' + hook)
  }
  popTarget()
}
复制代码

invokeWithErrorHandling实现

export function invokeWithErrorHandling (
  handler: Function,
  context: any,
  args: null | any[],
  vm: any,
  info: string
) {
  let res
  try {
     // 将handle方法绑定到context上并执行
    res = args ? handler.apply(context, args) : handler.call(context)
     // 如果返回值是promise的话,需要对异常进行一些捕获
    ...异常捕获内容
  } catch (e) {
    handleError(e, vm, info)
  }
  return res
} 
复制代码
  • 步骤
    • this.options中获取用户自定义的created方法
    • 如果有自定义方法就循环执行定义的的方法,并将方法都绑定到vm上
  • 作用: 主要是为了执行用户自定义的生命周期方法

defineReactive方法的解析

具体内容待续

  • 作用:给对应绑定一个可以被监听的属性
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享