• vue中相同逻辑如何抽离


    就是使用Vue.mixin方法(混入),其提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。说白了就是给每个生命周期,函数等等中间加入一些公共逻辑。

    //vue/src/core/global-api/mixin.js 
    
    import { mergeOptions } from '../util/index'
    
    export function initMixin (Vue: GlobalAPI) {
      Vue.mixin = function (mixin: Object) {
        this.options = mergeOptions(this.options, mixin)
        return this
      }
    }
    
    --------------------------------------------------------------------
    //vue/src/core/util/options.js /
    /**
     * Merge two option objects into a new one.
     * Core utility used in both instantiation and inheritance.
     */
    export function mergeOptions (
      parent: Object,
      child: Object,
      vm?: Component
    ): Object {
      if (process.env.NODE_ENV !== 'production') {
        checkComponents(child)
      }
    
      if (typeof child === 'function') {
        child = child.options
      }
    
      normalizeProps(child, vm)
      normalizeInject(child, vm)
      normalizeDirectives(child)
    
      // Apply extends and mixins on the child options,
      // but only if it is a raw options object that isn't
      // the result of another mergeOptions call.
      // Only merged options has the _base property.
      if (!child._base) {
        if (child.extends) { //递归合并extends
          parent = mergeOptions(parent, child.extends, vm)
        }
        if (child.mixins) { //递归合并mixin
          for (let i = 0, l = child.mixins.length; i < l; i++) {
            parent = mergeOptions(parent, child.mixins[i], vm)
          }
        }
      }
    
      const options = {} //属性和生命周期的合并
      let key
      for (key in parent) {
        mergeField(key)
      }
      for (key in child) {
        if (!hasOwn(parent, key)) {
          mergeField(key)
        }
      }
      function mergeField (key) {
        const strat = strats[key] || defaultStrat
        options[key] = strat(parent[key], child[key], vm, key)
      }
      return options
    }
  • 相关阅读:
    Day 15 模块
    Day 14 三元运算符,列表推导式,内置函数
    Day 13 可迭代对象,迭代器对象,for循环迭代,生成器对象,枚举对象
    Day 12 开放封闭原则,装饰器初识
    Day 11 函数对象,函数嵌套,作用域,闭包
    Day 10 函数的形参,实参
    Day 09 函数基础
    Day 08 文件操作模式,文件复制,游标
    HTTP协议
    11,.JS-DOM价绍
  • 原文地址:https://www.cnblogs.com/qq965921539/p/13412596.html
Copyright © 2020-2023  润新知