【若川视野 x 源码共读】第23期 | 为什么 Vue2 this 能够直接获取到 data 和 methods

134 阅读2分钟

本文参加了由公众号@若川视野 发起的每周源码共读活动,点击了解详情一起参与。

学习目标

  1. 如何学习调试 vue2 源码
  2. data 中的数据为什么可以用 this 直接获取到
  3. methods 中的方法为什么可以用 this 直接获取到
  4. 学习源码中优秀代码和思想,投入到自己的项目中

Vue 2.0 源码

构造方法Vue

function Vue (options) {
  // 使用Vue的时候需要判断一下是不是Vue的实例
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  // 这里会初始化 Vue里面的值
  this._init(options)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

每个项目在最开始的时候,都会初始化一个Vue的实例,方便我们操作Vue的方法。

初始化Vue

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

我们在这个函数中可以看到Vue最开始执行的一些函数,我们看最关键的initState函数。

initState 函数

export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  // 初始化 Props
  if (opts.props) initProps(vm, opts.props)
  // 初始化 methods
  if (opts.methods) initMethods(vm, opts.methods)
  // 监测数据
  if (opts.data) {
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }
  // 初始化 computed
  if (opts.computed) initComputed(vm, opts.computed)
  // 初始化 watch
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

因为我们要探索为啥Vue可以通过this获取到datamethod中的数据或方法,我们重点看initMethodsinitData两个函数。

initMethods 函数

function initMethods (vm: Component, methods: Object) {
  const props = vm.$options.props
  for (const key in methods) {
    if (process.env.NODE_ENV !== 'production') {
      // 判断 methods 中的每一项是不是函数,如果不是警告。
      if (typeof methods[key] !== 'function') {
        warn(
          `Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
          `Did you reference the function correctly?`,
          vm
        )
      }
      // 判断 methods 中的每一项是不是和 props 冲突了,如果是,警告。
      if (props && hasOwn(props, key)) {
        warn(
          `Method "${key}" has already been defined as a prop.`,
          vm
        )
      }
      // 判断 methods 中的每一项是不是已经在 new Vue实例 vm 上存在,而且是方法名是保留的 _ $ (在JS中一般指内部变量标识)开头,如果是警告。
      if ((key in vm) && isReserved(key)) {
        warn(
          `Method "${key}" conflicts with an existing Vue instance method. ` +
          `Avoid defining component methods that start with _ or $.`
        )
      }
    }
    vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
  }
}

我们可以看到这个函数执行到最后会调用bind函数,那么我们去找到这个函数。

bind 函数

打开 /shared/utils.js文件

// bind 的垫片
function polyfillBind (fn: Function, ctx: Object): Function {
  function boundFn (a) {
    const l = arguments.length
    return l
      ? l > 1
        ? fn.apply(ctx, arguments)
        : fn.call(ctx, a)
      : fn.call(ctx)
  }

  boundFn._length = fn.length
  return boundFn
}

// 让fn的this指向ctx
function nativeBind (fn: Function, ctx: Object): Function {
  return fn.bind(ctx)
}

// 重写Function上的bindF方法
export const bind = Function.prototype.bind
  ? nativeBind
  : polyfillBind

我们发现bind函数调用了原生的bind方法,polyfillBind 为了兼容以前Function没有的bind函数。这也是为什么我们可以通过this取到methods中函数的原因。

initData 函数

function initData (vm: Component) {
  let data = vm.$options.data
  // 先给 _data 赋值,以备后用。
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
    // 最终获取到的 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
  // 遍历 data ,其中每一项:
  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') {
      // 如果和 methods 冲突了,报警告。
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    // 如果和 props 冲突了,报警告。
    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)) {
      // 不是内部私有的保留属性,做一层代理,代理到 _data 上。
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  // 最后监测 data,使之成为响应式的数据。
  observe(data, true /* asRootData */)
}

我们发现在这个函数中,如果一切顺利,会调用getData函数。

getData 函数
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()
  }
}

我们看到data中的数据也是被挂载到了Vue上面,这也是为什么this可获取data中的数据的原因。

总结

通过逐步分析Vue 2.0的源码,我们发现Vue2.0的源码上data和methods是通过call或bind改变this指向,让Vue的实例可以访问到data和methods中的数据。