1.本文将讲述 方法 Vue.extend Vue.mixin 与 new Vue({mixins:[], extend:{}})的区别与原理

先回顾一下 Vue.mixin 官网如下描述:

Vue.mixin( mixin )全局注册一个混入,影响注册之后所有创建的每个 Vue 实例。插件作者可以使用混入,向组件注入自定义的行为。

既然可以影响到注册后的所有实例,那么该方法注入的方法和属性都存放在哪里呢(构造函数的options属性上),我们一起来看看该方法的定义

     Vue.mixin = function (mixin) {
//mergeOption,将Vue构造函数的Options属性与传入的mixin参数进行合并,
//合并之后再复制给Vue构造函数的Options属性
this.options = mergeOptions(this.options, mixin);
return this
};

为什么Vue.mixin方法将mixin合并至Vue.options就能影响注册之后的所有实例呢,让我们看看Vue实例化的过程(将构造函数的options属性与实例化参数合并后付给实例的$options属性

 

    function Vue(options) {
//调用_init方法
this._init(options);
} Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid$++; var startTag, endTag; // a flag to avoid this being observed 标记该对象是一个Vue实例
vm._isVue = true;
// merge options
if (options && options._isComponent) { //组件实例化过程,即Vue.extend返回对象--稍后解释
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {//将构造函数的options属性与实例化参数合并后付给实例的$options属性 ,该属性会在函数initState中进行初始化
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
{
initProxy(vm);
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, 'created'); /* istanbul ignore if */
if ("development" !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(("vue " + (vm._name) + " init"), startTag, endTag);
} if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};

     Vue.extend-- 使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象 

该方法返回一个与Vue具有相同功能的构造函数(其实为创建了一个组件)-属性options是 合并  基础 Vue 构造器 与 extend的参数 的对象,

 Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
//将调用函数付给Super
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 ("development" !== 'production' && name) {
validateComponentName(name);
}
//创建组件Sub
var Sub = function VueComponent(options) {
this._init(options);
};
       //为组件添加对应的属性与方法
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
//合并super的options与extend的入参并赋值给Sub的options属性
Sub.options = mergeOptions(
Super.options,
extendOptions
);
//在sub上保存Super的信息
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$(Sub);
}
if (Sub.options.computed) {
initComputed$(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
//如果有组件名称,将该组件挂载到sub.options.components上。以便可在组件内使用
          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.
//保存option信息。以便在render的时候生成最新的options选项
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options); // cache constructor
cachedCtors[SuperId] = Sub;
return Sub //返回sub构造函数
};

Vue.component( id, [definition] ) 注册或获取全局组件。注册还会自动使用给定的id设置组件的名称,第二个参数可以是Object也可以调用Vue.extend 返回的构造函数,返回组件

调用Vue.component 将调用Vue.extend生成一个组件(构造函数),该组件将赋值给Vue.options.components[id],由于在实例化时,将合并构造函数的options至实例对象的$options上,所有通过通过全局构造函数Vue创建的组件或者视图都可以运用该组件,

 var ASSET_TYPES = [
'component',
'directive',
'filter'
];
//定义 Vue.component . Vue.directive Vue.filter ASSET_TYPES.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if ("development" !== 'production' && type === 'component') {
//对组件的命名规范进行验证
validateComponentName(id);
}
if (type === 'component' && isPlainObject(definition)) {
//如果第二个参数是一个Object 调用 Vue.extend(definition)生成一个构造函数 this.options._base === Vue
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
//将Vue.options.components[id]赋值为 组件构造函数
this.options[type + 's'][id] = definition;
return definition
}
};
});
}

由以上代码可见  Vue.component返回的组件即为  Vue.extend创建的构造函数 -再次命名为subVue,subVue具有与Vue一样的方法和属性,所以可调用subVue.component,subVue.extend创建组件,调用subVue.component,subVue.extend创建的组件组件将存放于subVue.options上,所以在通过subVue创建的组件,只能用于subVue实例化传入字符串模板的中模板使用,或者subVue.component,subVue.extend创建的组件实例化传入的字符串模板中使用。

   new Vue({mixins:[], extend:{}})

实例化选项mixins , extend将在init函数中通过mergeOptions合并至实例属性$options,他们的区别是extend为options对象,mixins为options数组,同时 extend的方法将比mixins先执行,但他们都会在  Vue.extend 与  Vue.mixin之后  执行

Vue.mixin Vue.extend(Vue.component)的原理与区别的更多相关文章

  1. vue.mixin与vue.extend

    vue.mixin 全局注册一个混合,影响注册之后所有创建的每个 Vue 实例.谨慎使用全局混合对象,因为会影响到每个单独创建的 Vue 实例(包括第三方模板).大多数情况下,只应当应用于自定义选项, ...

  2. vue中extend/component/mixins/extends的区别

    vue中extend/component/mixins/extends的区别 教你写一个vue toast弹窗组件 Vue.extend构造器的延伸

  3. Vue.2.0.5-深入响应式原理

    大部分的基础内容我们已经讲到了,现在讲点底层内容.Vue 最显著的一个功能是响应系统 -- 模型只是普通对象,修改它则更新视图.这会让状态管理变得非常简单且直观,不过理解它的原理以避免一些常见的陷阱也 ...

  4. vue里extend、mixins、extends的区别

    1.extend Vue.extend使用基础 Vue 构造器,创建一个"子类".参数是一个包含组件选项的对象. // Vue.extend // 创建构造器 var Profil ...

  5. 理解Vue.mixin,带你正确的偷懒

    关于Vue.mixin在vue官方文档中是这么解释的: 混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能.一个混入对象可以包含任意组件选项.当组件使用混入对象时,所有 ...

  6. vue第七单元(vue的单文件组件形式-单文件组件的加载原理-vue-cli构建的开发环境以及生命周期)

    第七单元(vue的单文件组件形式-单文件组件的加载原理-vue-cli构建的开发环境以及生命周期) #课程目标 掌握安装 vue-cli 命令行工具的方法,掌握使用命令行在本地搭建开发环境,使用命令行 ...

  7. "[Vue warn]: Failed to mount component: template or render function not defined"错误的解决

    VUE中动态路由出错: vue.esm.js?a026: [Vue warn]: Failed to mount component: template or render function not ...

  8. vue mixin使用

    1.概述 将一些公用方法引入到不同的组件中. 2.引入方式 (1)全局引入 // 注册全局Mixin Vue.mixin({ methods: { $touch: function() { // 用以 ...

  9. Vue报错之"[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead......"

    一.报错截图 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the p ...

随机推荐

  1. Oracle 知识积累

    1.oracle存储过程中is和as的区别 在存储过程(PROCEDURE)和函数(FUNCTION)中没有区别,在视图(VIEW)中只能用AS不能用IS,在游标(CURSOR)中只能用IS不能用AS ...

  2. IOS - 绘制文字 drawInRect: withFont: not working

    在图形绘制中,我们经常会需要绘制文本,但我在给PDF上绘制Text时,始终绘制不上, 使用过: [str drawInRect:cubeRect withAttributes:attrs]; CGCo ...

  3. Python-基础-day1

    一.python的介绍 1.python的出现与应用场景 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆(中文名字:龟叔)为了在阿姆斯 ...

  4. C++调用C#编写的DLL【转】

    1.打开VS新建项目 2.在新建项目窗口中选择其他语言->Visual C++->Win 32控制台应用程序,设置名称:MathCon,设置解决方案名:MathCon,这个名字随便你自己取 ...

  5. 【hdu 6333】Harvest of Apples

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 假设T[i][j]表示的是杨辉三角第i层前j项的和. 会发现它同样满足杨辉三角的性质. 即 T[i][j] = T[i-1][j-1 ...

  6. Jquery Math ceil()、floor()、round()比较与用法

    Math.ceil():向上取值 如:Math.ceil(2.1) --  结果为  3 Math.ceil(-2.1)  -- 结果为-2 结论:正入 负舍 Math.floor(): 先下取值 入 ...

  7. Cannot Allocate New Log

    http://www.itpub.net/thread-1842569-1-1.html http://czmmiao.iteye.com/blog/2277675

  8. JavaScript中==和===区别

    在我们的日常编码中对于===是不常用的,但是它很重要 ===:表示绝对相等(严格) !==:表示不绝对相等 ==:表示相等(不严格) !=:表示不相等 看一下列子: null==undefined   ...

  9. hdu 5335 Walk Out (2015 Multi-University Training Contest 4)

    Walk Out                                                                         Time Limit: 2000/10 ...

  10. C# 用ManulResetEvent 控制Thread的 Suspend、Resume

    class Program { static void Main(string[] args) { Thread thread = new Thread(Work); thread.Start(); ...