Westore 開源兩天就突破了 1000 star,還登頂過Github日榜第一名。期間受到了海量關(guān)注,收到了大量的中肯和實(shí)用的反饋和意見。小程序插件開發(fā)的訴求是非常重要的意見之一。所以我馬不停蹄地努力連夜更新,看 Github 提交記錄就知道我凌晨 3 點(diǎn)鐘有合并 PR,也有提交代碼 = =!
先回顧一下小程序現(xiàn)有的痛點(diǎn):
所以沒使用 westore 的時(shí)候經(jīng)??梢钥吹竭@樣的代碼:

使用 Westore 對編程體驗(yàn)的改善:

上面兩種方式也可以混合使用。
這里需要特別強(qiáng)調(diào),雖然 this.update 可以兼容小程序的 this.setData 的方式傳參,但是更加智能,this.update 會按需 Diff 或者 透傳給 setData。原理:
再舉個(gè)例子:
this.store.data.motto = 'Hello Store222'
this.store.data.b.arr.push({ name: 'ccc' })
this.update()
復(fù)制代碼
等同于
this.update({
motto:'Hello Store222',
[`b.arr[${this.store.data.b.arr.length}]`]:{name:'ccc'}
})
復(fù)制代碼
|
插件開發(fā)者可以像開發(fā)小程序一樣編寫一個(gè)插件并上傳代碼,在插件發(fā)布之后,其他小程序方可調(diào)用。小程序平臺會托管插件代碼,其他小程序調(diào)用時(shí),上傳的插件代碼會隨小程序一起下載運(yùn)行。
Westore 提供的目錄如下:
|--components
|--westore
|--plugin.json
|--store.js
復(fù)制代碼
創(chuàng)建插件:
import create from '../../westore/create-plugin'
import store from '../../store'
//最外層容器節(jié)點(diǎn)需要傳入 store,其他組件不傳 store
create(store, {
properties:{
authKey:{
type: String,
value: ''
}
},
data: { list: [] },
attached: function () {
// 可以得到插件上聲明傳遞過來的屬性值
console.log(this.properties.authKey)
// 監(jiān)聽所有變化
this.store.onChange = (detail) => {
this.triggerEvent('listChange', detail)
}
// 可以在這里發(fā)起網(wǎng)絡(luò)請求獲取插件的數(shù)據(jù)
this.store.data.list = [{
name: '電視',
price: 1000
}, {
name: '電腦',
price: 4000
}, {
name: '手機(jī)',
price: 3000
}]
this.update()
//同樣也直接和兼容 setData 語法
this.update(
{ 'list[2].price': 100000 }
)
}
})
復(fù)制代碼
|
在你的小程序中使用組件:
<list auth-key="{{authKey}}" bind:listChange="onListChange" />
復(fù)制代碼
這里來梳理下小程序自定義組件插件怎么和使用它的小程序通訊:
這么方便簡潔還不趕緊試試 Westore插件開發(fā)模板 !
插件內(nèi)所有組件公用的 store 和插件外小程序的 store 是相互隔離的。
| 名稱 | 描述 |
|---|---|
| onLoad | 監(jiān)聽頁面加載 |
| onShow | 監(jiān)聽頁面顯示 |
| onReady | 監(jiān)聽頁面初次渲染完成 |
| onHide | 監(jiān)聽頁面隱藏 |
| onUnload | 監(jiān)聽頁面卸載 |
| 名稱 | 描述 |
|---|---|
| created | 在組件實(shí)例進(jìn)入頁面節(jié)點(diǎn)樹時(shí)執(zhí)行,注意此時(shí)不能調(diào)用 setData |
| attached | 在組件實(shí)例進(jìn)入頁面節(jié)點(diǎn)樹時(shí)執(zhí)行 |
| ready | 在組件布局完成后執(zhí)行,此時(shí)可以獲取節(jié)點(diǎn)信息(使用 SelectorQuery ) |
| moved | 在組件實(shí)例被移動到節(jié)點(diǎn)樹另一個(gè)位置時(shí)執(zhí)行 |
| detached | 在組件實(shí)例被從頁面節(jié)點(diǎn)樹移除時(shí)執(zhí)行 |
由于開發(fā)插件時(shí)候的組件沒有 this.page,所以 store 是從根組件注入,而且可以在 attached 提前注入:
export default function create(store, option) {
let opt = store
if (option) {
opt = option
originData = JSON.parse(JSON.stringify(store.data))
globalStore = store
globalStore.instances = []
create.store = globalStore
}
const attached = opt.attached
opt.attached = function () {
this.store = globalStore
this.store.data = Object.assign(globalStore.data, opt.data)
this.setData.call(this, this.store.data)
globalStore.instances.push(this)
rewriteUpdate(this)
attached && attached.call(this)
}
Component(opt)
}
復(fù)制代碼
|