new Vue发生了什么

关键词:当执行new Vue时,实际上是执行了_init方法。_init方法会做一堆初始化工作,首先是对options的合并,然后是一系列 init 方法,对data进行proxy处理和响应式处理observe,最后调用$mount做挂载。

new Vue发生了什么

从入口代码开始分析,new Vue背后发生了哪些事情。

入口代码文件src/core/instance/index.js(Vue 定义)

Vue 实际上就是function实现的class,执行new Vue的时候执行了function,然后执行this._initoptions传入,this._init是一个 Vue 原型上的方法,是在initMixin,也就是src/core/instance/init.js中定义的。

// src/core/instance/index.js
import { initMixin } from './init'
import { stateMixin } from './state'

function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

initMixin(Vue)
stateMixin(Vue)

export default Vue

src/core/instance/init.js文件解析

在原型上定义了_init方法,也就是说走到了initMixin(Vue)时,执行了_init方法。

_init方法做了很多初始化的工作,例如:

  1. 定义uid
  2. 合并options。将传入的options merge 到$options上,所以可以通过$options.el访问到代码中定义的el,通过$options.data访问到我们定义的data
  3. 初始化函数(生命周期、事件中心、renderstate),初始化结束后判断$options有没有el。调用vm.$mount(vm.$options.el)进行挂载,在页面上可以看到字符串渲染到页面上。$mount方法是整个做挂载的方法(是个重点)。
export 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 */
    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)
    }
  }
}

src/core/instance/state.js文件解析

问:为什么在mounted(){console.log(this.message)}可以访问到message
答:(1)初始化时有一个initState,这个函数是定义在src/core/instance/state.js中。在initState()中,判断options,如果定义props则初始化props,定义了methods初始化methods,定义了data初始化data

export function initState (vm: Component) {
  vm._watchers = []
  const 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)
  }
}

(2)在initData中,从$options.data中拿到data,就是我们定义的data(){return {message:'Hello Vue!'}}。然后判断data是不是一个function(正常data是一个函数而不是对象),是函数则调用getDatagetData中调用call方法,返回对象,赋值给vm._datadata,如果不是对象就会报警告。然后拿到对象的keypropsmethods并进行对比,判断是否重名。为什么不能重名?因为他们最终都挂载到vm上,也就是当前实例上。实现是用proxy(vm,`_data`,key)实现。

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== 'production' && warn(
      'data functions should return an object:/n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    )
  }
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}

export function getData (data: Function, vm: Component): any {
  // #7573 disable dep collection when invoking data getters
  pushTarget()
  try {
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, `data()`)
    return {}
  } finally {
    popTarget()
  }
}

(3)proxy通过sharedPropertyDefinition对象定义了getset两个函数,运行Object.defineProperty(target, key, sharedPropertyDefinition)方法代理了targetkey,就是对targetkey做了一层访问getsettarget就是vmvm.keyget会执行return this[sourceKey][key],也就是说访问vm.key就是会访问this[sourceKey][key]sourceKey就是传入_data,所以访问vm.message实际上就会访问vm._data.message,即mounted(){console.log(this.message);console.log(this._data.message)}

// 根据上面 proxy(vm, `_data`, key),就是把`_data`作为sourceKey传入。
export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值