vue methods&props&dataをthisにマッピングする方法

8660 ワード

vue/src/core/instance/state.js
export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  // map props to this
  if (opts.props) initProps(vm, opts.props)
  // map methos to this
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
  // map data to this
    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)
  }
}

map props to this
    // static props are already proxied on the component's prototype
    // during Vue.extend(). We only need to proxy props defined at
    // instantiation here.
    if (!(key in vm)) {
      proxy(vm, `_props`, key)
    }

map methods to this
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)

map data to this
proxy(vm, `_data`, key)

proxy原理
const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

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

NOTE:data methods props keyは繰り返さないでください.そうしないと上書きされます.dataの優先度が最も高いです.