new Vue()、component
首先我們來約定一個選項對象 baseOptions,后面的代碼會用到.
let options = { template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White', alias: 'Heisenberg' } }, created(){ console.log('onCreated-1'); } };
new Vue() source:vue/src/core/instance/index.js
實例化一個組件.
new Vue(baseOptions); // -> onCreated-1 component source:vue/src/core/global-api/assets.js
Vue.component 是用來注冊或獲取全局組件的方法,其作用是將通過 Vue.extend 生成的擴展實例構造器注冊(命名)為一個組件.全局注冊的組件可以在所有晚于該組件注冊語句構造的Vue實例中使用.
Vue.component('global-component', Vue.extend(baseOptions)); //傳入一個選項對象(自動調用 Vue.extend),等價于上行代碼. Vue.component('global-component', baseOptions); // 獲取注冊的組件(始終返回構造器) var MyComponent = Vue.component('my-component')
當我們需要在其他頁面‘擴展'或者叫‘混合'baseOptions時,Vue中提供了多種的實現方式:extend,mixins,extends.
extend source:vue/src/core/global-api/extend.js
可以擴展 Vue 構造器,從而用預定義選項創建可復用的組件構造器。
let BaseComponent = Vue.extend(baseOptions); //基于基礎組件BaseComponent,再擴展新邏輯. new BaseComponent({ created(){ //do something console.log('onCreated-2'); } //其他自定義邏輯 }); // -> onCreated-1 // -> onCreated-2
mixins
mixins 選項接受一個混合對象的數組。這些混合實例對象可以像正常的實例對象一樣包含選項,他們將在 Vue.extend() 里最終選擇使用相同的選項合并邏輯合并。
new Vue({ mixins: [baseOptions], created(){ //do something console.log('onCreated-2'); } //其他自定義邏輯 }); // -> onCreated-1 // -> onCreated-2
extends
這和 mixins 類似,區別在于,組件自身的選項會比要擴展的源組件具有更高的優先級.
官方文檔是這么寫的,除了優先級,可能就剩下接受參數的類型吧,mixins接受的是數組.
new Vue({ extends: baseOptions, created(){ //do something console.log('onCreated-2'); } //其他自定義邏輯 }); // -> onCreated-1 // -> onCreated-2
從結果上看,三種方式都能實現需求,但是形式卻有不同.
從源碼來看通過extend,extends和mixins三種方式接收的options,最終都是通過mergeOptions進行合并的.差異只是官方文檔中提到的優先級不同extend > extends > mixins. 所以,如果是簡單的擴展組件功能,三個方式都可以達到目的.
而這三種方式使用場景上細化的區分,目前我也蒙圈中...
//幾種方式的不同示例:
https://jsfiddle.net/willnewi...
選項對象合并策略 Vue.config.optionMergeStrategies
上面提到的選項對象,是在mergeOptions中按照一定策略進行合并的.
打印Vue.config.optionMergeStrategies,你會看默認的optionMergeStrategies如下:
mergeAssets
mergeAssets合并方法里,用到了原型委托.他會先把父組件的屬性放在創建的新對象的原型鏈上.然后擴展新對象
對象里查找屬性的規則 :舉個例子,當查找一個屬性時,如 obj[a] ,如果 obj 沒有 a 這個屬性,那么將會在 obj 對象的原型里找,如果還沒有,在原型的原型上找,直到原型鏈的盡頭,如果還沒有找到,返回 undefined。
function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } function mergeAssets (parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : res }
總結
如果按照優先級去理解,當你需要繼承一個組件時,可以使用Vue.extend().當你需要擴展組件功能的時候,可以使用extends,mixins.但目前為止還沒有碰到完美詮釋他們的場景,抱歉,能力有限😂
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com