Vue源码学习系列03——Vue构造函数解析(一): 选项规范化(normalize)

打个小广告哈,最近做了个小程序,来测测你的工作性价比吧~(微信扫码打开小程序即可)

工作性价比评估器


上一节分析了,Vue的构造函数中,只有一句this._init(options),可见这行代码的重要性。今天我们就来详细的看看这个函数主要干了什么事。为了不那么抽象,我会用一个简单的例子来贯穿整个讲解。这个例子非常简单。


var app = new Vue({
   
  el: '#app',
  data(){
   
    return {
   
      name: 'hello'
    }
  }
})

如上一节所说,这个 _init 方法在 initMixin 中。Ok,我们来看看:

Vue.prototype._init = function (options?: Object) {
   
    const vm: Component = this
    // a uid
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   
      startTag = `vue-perf-start:${
     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(`vue ${
     vm._name} init`, startTag, endTag)
    }

    if (vm.$options.el) {
   
      vm.$mount(vm.$options.el)
    }
  }

首先,把当前实例(this)赋给vm 变量,在给这个实例的uid自增。接下来我们会看到这么些东西,

let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   
  startTag = `vue-perf-start:${
     vm._uid}`
  endTag = 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值