从源码来认知 Vue.util.extend 与 Vue.extend 的区别

关于这个问题,我百度了一下,貌似很少有人去探究这个问题,既然查不到,那么我们就从源码来学习,这就是一个比较好的方法。源码能够给你答案!

console.log(Vue.util.extend);
console.log(Vue.extend);
/**
   * Mix properties into target object.
   */
   
  //Vue.util.extend
  //其实就是拷贝一份,以后可以直接调用即可
  function extend (to, _from) {
    for (var key in _from) {
      to[key] = _from[key];
    }
    return to
  }
  
  /**
     * Class inheritance
     */
     
	//Vue.extend
    Vue.extend = function (extendOptions) {
      extendOptions = extendOptions || {};
      var Super = this;
      var SuperId = Super.cid;
      var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
      if (cachedCtors[SuperId]) {
        return cachedCtors[SuperId]
      }
  
      var name = extendOptions.name || Super.options.name;
      if (name) {
        validateComponentName(name);
      }
  
      var Sub = function VueComponent (options) {
        this._init(options);
      };
      Sub.prototype = Object.create(Super.prototype);
      Sub.prototype.constructor = Sub;
      Sub.cid = cid++;
      Sub.options = mergeOptions(
        Super.options,
        extendOptions
      );
      Sub['super'] = Super;
  
      // For props and computed properties, we define the proxy getters on
      // the Vue instances at extension time, on the extended prototype. This
      // avoids Object.defineProperty calls for each instance created.
      if (Sub.options.props) {
        initProps$1(Sub);
      }
      if (Sub.options.computed) {
        initComputed$1(Sub);
      }
  
      // allow further extension/mixin/plugin usage
      Sub.extend = Super.extend;
      Sub.mixin = Super.mixin;
      Sub.use = Super.use;
  
      // create asset registers, so extended classes
      // can have their private assets too.
      ASSET_TYPES.forEach(function (type) {
        Sub[type] = Super[type];
      });
      // enable recursive self-lookup
      if (name) {
        Sub.options.components[name] = Sub;
      }
  
      // keep a reference to the super options at extension time.
      // later at instantiation we can check if Super's options have
      // been updated.
      Sub.superOptions = Super.options;
      Sub.extendOptions = extendOptions;
      Sub.sealedOptions = extend({}, Sub.options);
  
      // cache constructor
      cachedCtors[SuperId] = Sub;
      return Sub
    };
  }

单元测试

关于Vue.extend我们以下面这个单元测试例子来讲解:

由下图可知,我们获取到了HelloWorld的构造函数,然后再拿到组件。简单来说,你可以在任何地方,拿到任何组件,这对于单元测试方面是比较方便的,你可以拿到任何组件里的方法进行测试。

学如逆水行舟,不进则退
发布了581 篇原创文章 · 获赞 1694 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/104815722