细读Vue2.6.14 Core 源码(5): initState

717 阅读2分钟

细读Vue2.6.14 Core 源码(5): initState

    /**
        @date 2021-09-05
        @description 细读Vue2.6.14 Core 源码(5): initState
    */

壹(序)

之前的章节走完了初始化(调用 created 钩子函数),在 beforeCreatecreated 之间,有一步是调用 initState , 这一步处理了 props, methods, data, computed, watch, 至关重要,所以单独抽一章讲解。

贰(initState)

export function initState(vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  // 处理 props,设置为响应式并代理到 vm 实例
  if (opts.props) initProps(vm, opts.props)
  // 处理 methods
  if (opts.methods) initMethods(vm, opts.methods)
  // 处理 data
  if (opts.data) {
    initData(vm)
  } else {
    // new Vue 产生的实例会走这里
    observe(vm._data = {}, true /* asRootData */)
  }
  // 处理 computed
  if (opts.computed) initComputed(vm, opts.computed)
  // 处理 watch
  // 使用 createWatcher 函数($watch)处理
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

叁(initProps)

function initProps(vm: Component, propsOptions: Object) {
  // 获取 props data
  const propsData = vm.$options.propsData || {}
  // vm 声明 _props
  const props = vm._props = {}
  // 缓存 props 的 key,之后更新时直接使用,不需要重新获取,有利于性能
  const keys = vm.$options._propKeys = []
  // 是否是 root Vue 实例,也就是 new Vue 产生的实例
  const isRoot = !vm.$parent
  // root instance props should be converted
  if (!isRoot) {
    toggleObserving(false)
  }
  for (const key in propsOptions) {
    // 缓存key
    keys.push(key)
    const value = validateProp(key, propsOptions, propsData, vm)
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      // 转换 key 为 连字符样式(helloWorld => hello-world)
      const hyphenatedKey = hyphenate(key)
      // 检查是否是 Vue 保留字符(style, class, ref, scope...)
      if (isReservedAttribute(hyphenatedKey) ||
        config.isReservedAttr(hyphenatedKey)) {
        warn(
          `"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
          vm
        )
      }
      // 响应式
      defineReactive(props, key, value, () => {
        if (!isRoot && !isUpdatingChildComponent) {
          warn(
            `Avoid mutating a prop directly since the value will be ` +
            `overwritten whenever the parent component re-renders. ` +
            `Instead, use a data or computed property based on the prop's ` +
            `value. Prop being mutated: "${key}"`,
            vm
          )
        }
      })
    } else {
      defineReactive(props, key, value)
    }
    // 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)) {
      // 代理 key 到 vm上
      proxy(vm, `_props`, key)
    }
  }
  toggleObserving(true)
}

肆(initMethods)

function initMethods(vm: Component, methods: Object) {
  const props = vm.$options.props
  for (const key in methods) {
    // 非生产环境下的一些判断及报警告
    // 阅读这些也是挺重要的,毕竟开发是在非生产环境下,看了这些能明白你控制台报的警告是为什么,从哪儿来
    if (process.env.NODE_ENV !== 'production') {
      // 是否是 function
      if (typeof methods[key] !== 'function') {
        warn(
          `Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
          `Did you reference the function correctly?`,
          vm
        )
      }
      // key 是不是 props 的属性
      if (props && hasOwn(props, key)) {
        warn(
          `Method "${key}" has already been defined as a prop.`,
          vm
        )
      }
      // 检查 key 是否保留字段($/_)
      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 实例上
    vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
  }
}

伍(initData)

function initData(vm: Component) {
  let data = vm.$options.data
  // data 是一个 function还是一个 object
  // 从这里可以看到,如果一个组件的 data 是 pure object 而不是通过 function 返回的话
  // 那么所有复用此组件的地方,都是使用同一个 object,在 js 中,这样的情况不需多说
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  // 不是 pure object,则重置为空对象
  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/props/methods 重复 key 的警告问题
  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 中已经有当前 key
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    // props 中已经有当前 key
    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)) {
      // 代理 key 到 vm
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}

陆(initComputed)

function initComputed(vm: Component, computed: Object) {
  // $flow-disable-line
  // 初始化 watchers
  const watchers = vm._computedWatchers = Object.create(null)
  // computed properties are just getters during SSR
  const isSSR = isServerRendering()

  for (const key in computed) {
    const userDef = computed[key]
    // 获取 getter
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    if (process.env.NODE_ENV !== 'production' && getter == null) {
      warn(
        `Getter is missing for computed property "${key}".`,
        vm
      )
    }

    if (!isSSR) {
      // create internal watcher for the computed property.
      // 创建 watcher
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }

    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    // vm 实例上没有 [key] 属性
    if (!(key in vm)) {
      // 定义 computed,使用上面声明的 watcher
      defineComputed(vm, key, userDef)
    } else if (process.env.NODE_ENV !== 'production') {
      // key 已存在的警告
      if (key in vm.$data) {
        warn(`The computed property "${key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      } else if (vm.$options.methods && key in vm.$options.methods) {
        warn(`The computed property "${key}" is already defined as a method.`, vm)
      }
    }
  }
}

// defineComputed
export function defineComputed(
  target: any,
  key: string,
  userDef: Object | Function
) {
  const shouldCache = !isServerRendering()
  // 生成 getter 和 setter
  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  if (process.env.NODE_ENV !== 'production' &&
      sharedPropertyDefinition.set === noop) {
    sharedPropertyDefinition.set = function () {
      warn(
        `Computed property "${key}" was assigned to but it has no setter.`,
        this
      )
    }
  }
  // 拦截
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

// createComputedGetter
function createComputedGetter(key) {
  return function computedGetter() {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        // 由于 computed 是懒加载,所以此时才去调用 watcher 的 get 函数
        // 并且会将 dirty 设置为false
        // 在调用 update 时又会重新设置为 true
        // dirty 的作用就是 computed 的缓存功能,在一次更新中,只需要计算一次
        watcher.evaluate()
      }
      if (Dep.target) {
        // 依赖收集
        watcher.depend()
      }
      return watcher.value
    }
  }
}

终(导航)

细读Vue2.6.14 Core 源码(1): 入口

细读Vue2.6.14 Core 源码(2): After Vue

细读Vue2.6.14 Core 源码(3): initGlobalAPI

细读Vue2.6.14 Core 源码(4): _init

细读Vue2.6.14 Core 源码(5): initState

细读Vue2.6.14 Core 源码(6): defineReactive

细读Vue2.6.14 Core 源码(7): $mount

细读Vue2.6.14 Core 源码(8): $createElement