美文网首页
Vue 选项合并规则

Vue 选项合并规则

作者: 茂茂爱吃鱼 | 来源:发表于2018-11-27 16:00 被阅读0次
    • dataprovide 等选项使用 mergeDataOrFn
    • 生命周期钩子watch 合并为 数组,使得父子选项中的钩子函数都能够被执行
    • directivesfilterscomponents 等资源选项,父子选项将以原型链的形式被处理,这样才能够在任何地方都是用内置组件、指令等
    • propsmethodsinjectcomputed 等选项,父选项始终可用,但是子选项会覆盖同名的父选项字段
    • 以上没有提到的选项都使用默认 defaultStrat,该选项策略是:只要子选项不是 undefined 就是用子选项,否则使用父选项

    附上 mergeDataOrFn 的实现:

    export function mergeDataOrFn (
      parentVal: any,
      childVal: any,
      vm?: Component
    ): ?Function {
      if (!vm) {
        // in a Vue.extend merge, both should be functions
        if (!childVal) {
          return parentVal
        }
        if (!parentVal) {
          return childVal
        }
        // when parentVal & childVal are both present,
        // we need to return a function that returns the
        // merged result of both functions... no need to
        // check if parentVal is a function here because
        // it has to be a function to pass previous merges.
        return function mergedDataFn () {
          return mergeData(
            typeof childVal === 'function' ? childVal.call(this, this) : childVal,
            typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
          )
        }
      } else {
        return function mergedInstanceDataFn () {
          // instance merge
          const instanceData = typeof childVal === 'function'
            ? childVal.call(vm, vm)
            : childVal
          const defaultData = typeof parentVal === 'function'
            ? parentVal.call(vm, vm)
            : parentVal
          if (instanceData) {
            return mergeData(instanceData, defaultData)
          } else {
            return defaultData
          }
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:Vue 选项合并规则

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