在(zai)原生開發小程序(xu)(xu)的過(guo)程中,發現有(you)多個頁面(mian)都使(shi)用了(le)幾乎完全一樣的邏輯。由(you)于小程序(xu)(xu)官方并(bing)沒有(you)提供 Mixins 這種代(dai)碼復(fu)用機制,所(suo)以只能采(cai)用非常不優雅的復(fu)制粘貼(tie)(tie)的方式去“復(fu)用”代(dai)碼。隨著(zhu)功能越來越復(fu)雜,靠復(fu)制粘貼(tie)(tie)來維護代(dai)碼顯然不科學,于是(shi)便尋思著(zhu)如(ru)何(he)在(zai)小程序(xu)(xu)里面(mian)實現 Mixins。
Mixins 直譯過來是“混(hun)入”的意思,顧名思義就是把可復(fu)用(yong)(yong)的代(dai)碼混(hun)入當前的代(dai)碼里面(mian)。熟(shu)悉 VueJS 的同(tong)學應(ying)該清楚(chu),它提供了更強大了代(dai)碼復(fu)用(yong)(yong)能力(li),解(jie)耦了重復(fu)的模塊(kuai),讓系統維護更加方便優雅。
先看看在 VueJS 中(zhong)是怎么(me)使用(yong) Mixins 的(de)。
// define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
|
在上述(shu)的代碼(ma)中,首先定(ding)義了一個名為(wei) myMixin 的對象,里面定(ding)義了一些生命(ming)周期函數(shu)和方法。接著(zhu)在一個新建的組件(jian)里面直接通過 mixins: [myMixin] 的方式注入(ru),此時新建的組件(jian)便獲得了來自 myMixin 的方法了。
明(ming)白了(le)什么(me)是 Mixins 以后(hou),便可開始著手在(zai)小程序里面實現了(le)。
Mixins 也有一(yi)(yi)些小(xiao)小(xiao)的(de)(de)細節需要注意的(de)(de),就是關于生(sheng)命周期(qi)事件(jian)的(de)(de)執行(xing)順序。在(zai)上一(yi)(yi)節的(de)(de)例子中,我們在(zai) myMixin 里(li)定義(yi)了一(yi)(yi)個 created() 方(fang)法,這是 VueJS 里(li)面的(de)(de)一(yi)(yi)個生(sheng)命周期(qi)事件(jian)。如(ru)果我們在(zai)新建組(zu)件(jian) Component 里(li)面也定義(yi)一(yi)(yi)個 created() 方(fang)法,那么執行(xing)結果會是如(ru)何呢?
var Component = Vue.extend({
mixins: [myMixin],
created: function () {
console.log('hello from Component!')
}
})
var component = new Component()
// =>
// Hello from mixin!
// Hello from Component!
|
可以看運行(xing)結果是先輸出了來(lai)自(zi) Mixin 的 log,再輸出來(lai)自(zi)組件的 log。
除了生命周期(qi)函數以(yi)外,再看看對(dui)象屬性的混入(ru)結果:
// define a mixin object
const myMixin = {
data () {
return {
mixinData: 'data from mixin'
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin],
data () {
return {
componentData: 'data from component'
}
},
mounted () {
console.log(this.$data)
}
})
var component = new Component()
|
在 VueJS 中,會把(ba)來自 Mixins 和組件(jian)的對象屬(shu)性(xing)當中的內容(如 data, methods等)混(hun)合,以(yi)確(que)保兩邊的數(shu)據都同(tong)時存在。
經過上述的驗證,我們可(ke)以得到 VueJS 中關于 Mixins 運行機(ji)制的結論:
但是在(zai)(zai)小程(cheng)序(xu)中(zhong),這套機(ji)制會(hui)和 VueJS 的(de)有一(yi)(yi)點區(qu)別。在(zai)(zai)小程(cheng)序(xu)中(zhong),自(zi)定義的(de)方(fang)法是直接定義在(zai)(zai) Page 的(de)屬(shu)(shu)(shu)性(xing)當(dang)中(zhong)的(de),既不屬(shu)(shu)(shu)于生命周期類型屬(shu)(shu)(shu)性(xing),也不屬(shu)(shu)(shu)于對象類型屬(shu)(shu)(shu)性(xing)。為(wei)了不引入奇怪的(de)問題,我(wo)們為(wei)小程(cheng)序(xu)的(de) Mixins 運行機(ji)制多加一(yi)(yi)條:
在小程序中,每個(ge)頁面都由 Page(options) 函(han)數定(ding)義,而 Mixins 則作用(yong)于這個(ge)函(han)數當中的(de) options 對象。因此我們實(shi)現 Mixins 的(de)思路就(jiu)有了——劫持并改寫 Page 函(han)數,最(zui)后再重新把它釋放(fang)出(chu)來。
新建一個 mixins.js 文件:
// 保存原生的 Page 函數
const originPage = Page
Page = (options) => {
const mixins = options.mixins
// mixins 必須為數組
if (Array.isArray(mixins)) {
delete options.mixins
// mixins 注入并執行相應邏輯
options = merge(mixins, options)
}
// 釋放原生 Page 函數
originPage(options)
}
|
原理(li)很簡單,關鍵(jian)的地(di)方(fang)在于 merge() 函(han)數。merge 函(han)數即為(wei)小程序 Mixins 運行(xing)機(ji)制的具體實(shi)現,完(wan)全(quan)按照上一節(jie)總結的三條結論來進行(xing)。
// 定義小程序內置的屬性/方法
const originProperties = ['data', 'properties', 'options']
const originMethods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll', 'onTabItemTap']
function merge (mixins, options) {
mixins.forEach((mixin) => {
if (Object.prototype.toString.call(mixin) !== '[object Object]') {
throw new Error('mixin 類型必須為對象!')
}
// 遍歷 mixin 里面的所有屬性
for (let [key, value] of Object.entries(mixin)) {
if (originProperties.includes(key)) {
// 內置對象屬性混入
options[key] = { ...value, ...options[key] }
} else if (originMethods.includes(key)) {
// 內置方法屬性混入,優先執行混入的部分
const originFunc = options[key]
options[key] = function (...args) {
value.call(this, ...args)
return originFunc && originFunc.call(this, ...args)
}
} else {
// 自定義方法混入
options = { ...mixin, ...options }
}
}
})
return options
}
|
在小(xiao)程序的 app.js 里引(yin)入 mixins.js
require('./mixins.js')
撰寫一個 myMixin.js
module.exports = {
data: { someData: 'myMixin' },
onShow () { console.log('Log from mixin!') }
}
在 page/index/index.js 中使用
Page({
mixins: [require('../../myMixin.js')]
})

大功(gong)告成!此時(shi)小程序已經具備 Mixins 的(de)能力,對于(yu)代碼解耦(ou)與復用來說將會更加方便。