首页 > 语言 > JavaScript > 正文

Vue源码学习之初始化模块init.js解析

2024-05-06 15:24:53
字体:
来源:转载
供稿:网友

我们看到了VUE分了很多模块(initMixin()stateMixin()eventsMixin()lifecycleMixin()renderMixin()),通过使用Mixin模式,都是使用了JavaScript原型继承的原理,在Vue的原型上面增加属性和方法。我们继续跟着this._init(options)走,这个一点击进去就知道了是进入了init.js文件是在initMixin函数里面给Vue原型添加的_init方法。首先来从宏观看看这个init文件,可以看出主要是导出了两个函数:initMixin和resolveConstructorOptions,具体作用我们一步步来讨论。咋的一看这个文件,可能有些童鞋会看不明白函数参数括号里面写的是什么鬼,这个其实是应用了flow的类型检查,具体flow的使用这里就不介绍了,有兴趣的请移步:https://flow.org/en/

我们现在来看第一个函数initMixin,Vue实例在初始化的时候就调用了这个函数,

let uid = 0export function initMixin (Vue: Class<Component>) { Vue.prototype._init = function (options?: Object) {  const vm: Component = this  // a uid  vm._uid = uid++  let startTag, endTag  /* istanbul ignore if */  【**注:istanbul 是代码覆盖率检测工具,此注释为代码测试用**】  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {   startTag = `vue-perf-init:${vm._uid}`   endTag = `vue-perf-end:${vm._uid}`   mark(startTag)  }  // a flag to avoid this being observed  vm._isVue = true  // merge options  if (options && options._isComponent) {   // optimize internal component instantiation   // since dynamic options merging is pretty slow, and none of the   // internal component options needs special treatment.   initInternalComponent(vm, options)  } else {   vm.$options = mergeOptions(    resolveConstructorOptions(vm.constructor),    options || {},    vm   )  }  /* istanbul ignore else */  if (process.env.NODE_ENV !== 'production') {   initProxy(vm)  } else {   vm._renderProxy = vm  }  // expose real self  vm._self = vm  initLifecycle(vm)  initEvents(vm)  initRender(vm)  callHook(vm, 'beforeCreate')  initInjections(vm) // resolve injections before data/props  initState(vm)  initProvide(vm) // resolve provide after data/props  callHook(vm, 'created')  /* istanbul ignore if */  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {   vm._name = formatComponentName(vm, false)   mark(endTag)   measure(`${vm._name} init`, startTag, endTag)  }  if (vm.$options.el) {   vm.$mount(vm.$options.el)  } }}

我们本着宏观简化原则,这个函数里面前面有三个if判断工作我们可以先不细化讨论,大致第一个是用performance做性能监测,第二个合并option,第三个是做代理拦截,是ES6新特性,可参考阮一峰大神关于proxy的介绍【http://es6.ruanyifeng.com/#docs/proxy】。那么就进入了初始化函数主要点:

initLifecycle(vm) //生命周期变量初始化initEvents(vm) //事件监听初始化initRender(vm) //初始化渲染callHook(vm, 'beforeCreate')  //回调钩子beforeCreateinitInjections(vm) //初始化注入initState(vm)  // prop/data/computed/method/watch状态初始化initProvide(vm)   // resolve provide after data/propscallHook(vm, 'created')   //回调钩子created/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false) mark(endTag) measure(`${vm._name} init`, startTag, endTag)}if (vm.$options.el) { vm.$mount(vm.$options.el)}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选