前言
在業務中有沒有一個場景:多個頁面需要用到一樣的 data 和 method,或者生命周期都需要執行同樣的操作。我們在每個頁面都寫上重復的代碼,一但功能修改就要更新多個頁面,在后期維護起來會很麻煩。
那么有沒有一個方法將同樣的業務存放到一個文件中去管理呢?其實這個問題Vue已經告訴我們了,那就是Mixin功能。
Mixin是一種將可重用功能分布到組件的靈活方法。mixin對象可以包含任何組件選項。當組件使用mixin時,mixin中的所有選項都將被“混合”到組件的選項中。
實現功能
- 全局mixin方法
- 頁面mixins選項
優先級
在合並時發生沖突的優先級
使用設計
全局mixin:
頁面mixin:
實現思路
1.每個頁面的Page都是一個函數,可以對Page封裝,做一個代理
2.檢查是否有全局mixin,合並到頁面mixins中
3.獲取頁面的mixins,對data、method、lifecycle等進行合並
代碼實現

const nativePage = Page const lifecycle = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll'] let globalMixin = null //全局mixin方法 wx.mixin = function(config){ if(isType(config,'object')){ globalMixin = config } } //原生Page代理 Page = function (config) { let mixins = config.mixins //加入全局mixin if(globalMixin){ (mixins || (mixins=[])).unshift(globalMixin) } if (isType(mixins, 'array') && mixins.length > 0) { Reflect.deleteProperty(config, 'mixins') merge(mixins, config) } nativePage(config) } function merge(mixins, config) { mixins.forEach(mixin => { if (isType(mixin, 'object')) { //合並data、生命周期以及其他數據 Object.keys(mixin).forEach(key => { if (key === 'data') { config[key] = Object.assign({}, mixin[key], config[key]) } else if (lifecycle.includes(key)) { let nativeLifecycle = config[key] config[key] = function () { let arg = Array.prototype.slice.call(arguments) mixin[key].call(this, arg) return nativeLifecycle && nativeLifecycle.call(this, arg) } } else { config[key] = mixin[key] } }) } }) } //判斷類型工具 function isType(target, type) { let targetType = Object.prototype.toString.call(target).slice(8, -1).toLowerCase() type = type.toLowerCase() return targetType === type }
在 app.js 引入 mixin 文件就可以使用