美文网首页
vue源码分析(八)核心函数之initProps

vue源码分析(八)核心函数之initProps

作者: vue爱好者 | 来源:发表于2020-04-21 20:50 被阅读0次

我们打开文件 src/core/instance/state.js,找到定义initProps函数的代码:

function initProps (vm: Component, propsOptions: Object) {
  const propsData = vm.$options.propsData || {}
  const props = vm._props = {}
  // cache prop keys so that future props updates can iterate using Array
  // instead of dynamic object key enumeration.
  const keys = vm.$options._propKeys = []
  const isRoot = !vm.$parent
  // root instance props should be converted
 // 判断是否是根元素
  if (!isRoot) {
    toggleObserving(false)
  }
  for (const key in propsOptions) {
    keys.push(key)
    const value = validateProp(key, propsOptions, propsData, vm)
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      const hyphenatedKey = hyphenate(key)
      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.
   // 对每个props对象进行了监听
    if (!(key in vm)) {
      proxy(vm, `_props`, key)
    }
  }
  toggleObserving(true)
}

可以看到先是定义了一个 const isRoot = !vm.$parent 判断是否是根元素。之后调用 toggleObserving(false) 做了一个标识,紧接着用for in循环对每个props对象进行了监听 ,defineReactive函数的具体分析请点击查看。

相关文章

网友评论

      本文标题:vue源码分析(八)核心函数之initProps

      本文链接:https://www.haomeiwen.com/subject/msekyhtx.html