关于vue.js:new-Vue-发生了什么

2次阅读

共计 3978 个字符,预计需要花费 10 分钟才能阅读完成。

从入口代码开始剖析,咱们先来剖析 new Vue 背地产生了哪些事件。咱们都晓得,new 关键字在 Javascript 语言中代表实例化是一个对象,而 Vue 实际上是一个类,类在 Javascript 中是用 Function 来实现的,来看一下源码,在src/core/instance/index.js 中。

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')
  }
  // 当是实例化一个 vue 对象的时候
  // 调用了 init 办法配置 options
  this._init(options)
}

能够看到 Vue 只能通过 new 关键字初始化,而后会调用 this._init 办法,该办法在 src/core/instance/init.js 中定义

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)
  }
}

Vue 初始化次要就干了几件事件,合并配置,初始化生命周期,初始化事件核心,初始化渲染,初始化 data、props、computed、watcher 等等。

Vue 初始化咱们其实能够看到代码层级十分清晰。

// 对于 initState()这个办法。粗疏钻研下

问题:

咱们都理解在 vue 中如果想要拜访 Data 属性的值比方

    data() {return { b:1}
    }
    // 能够间接通过 this.b 拜访到这个值

可是为什么会这样呢?咱们来解析下 initData()这个函数

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) {// 如果 opts.data 存在那么就调用 initData()
    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)
  }
}

当初咱们来看看 initData 这个函数是做什么的
它接管了一个 vm 以后初始化的实例


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 */)
}

能够看到首先对于 data 是否是函数和对象进行了判断,如果 data 是非 object 和 function 会给 data 赋一个空值而后 warn。

之后能够看到 while 循环中 vue 对于 data 中的 key 值和 props 和 methods 做了是否反复命名的判断,如果没有反复那么就会执行


proxy(vm, `_data`, key)

proxy 又是什么呢?咱们来一起看看这个函数它做了什么。

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)
}

能够看到 proxy 函数接管三个参数,第一个参数是 vue 的实例

第二个参数是 sourceKey,也就是_data

第三个参数是 key 值,也就是对应 data 的 key 值。

它接管这三个 key 值并且在以后 vue 实例的 property 上定义了一个_data 的 key 值。value 是 sharedPropertyDefinition。

value 是 sharedPropertyDefinition 上有 get 和 set 办法

所以咱们在调用 this.data 的时候其实就是相当于在调用 this._data.data(set 同理)

data() {
    return {a:'3'}
}
// 底层实现
 Object.defineProperty(target, key, sharedPropertyDefinition)
 Object.defineProperty(vm, a, {get(val) {return this["_data"]["a"]
    },
    set(val) {this["_data"]["a"] = val
    }
})
正文完
 0