現(xiàn)在市面上有很多小程序的框架,看上去都挺高大上,但是實際用起來卻沒能真正解決項目的痛點,一般的都是為了寫法的方便都差不多運用vue的寫法進行改造,但是小程序本身具有組件化、開發(fā)、調試、發(fā)布、灰度、回滾、上報、統(tǒng)計、監(jiān)控和最近的云能力都很強悍,有時真沒必要還要去查看其它框架兩份文檔進行開發(fā)。
通過一段時間的小程序開發(fā),發(fā)現(xiàn)小程序現(xiàn)在的痛點其實真正是全局狀態(tài)管理和跨頁面通信,就像vuex進行狀態(tài)管理,雖然也有類似Redux狀態(tài)管理庫,但是使用起來比較麻煩。 有時候要定義一個全局的數(shù)據(jù)往往會弄緩存,但是這是下下策。
最近看到大神寫Westore框架或者說成是庫吧,嘛嘛再也不用擔心我編程了。下面就入門級的介紹一下這個框架的使用。
一、頁面結構

項目結構和原生的目錄沒有區(qū)別,只不過主要多加了在utils里面的diff.js、create.js以及store.js。里面的diff是核心的庫文件,create主要是頁面注冊用的,而store就是管理全局的數(shù)據(jù)中心。是不是一目了然。
二、頁面注冊及組件注冊
創(chuàng)建頁面
創(chuàng)建 Page 只需傳入兩個參數(shù),store 從根節(jié)點注入,所有子組件都能通過 this.store 訪問。原生的方法還是一樣使用,不影響。 this.update()類似this.setData()但是 this.update 調用的 setData 是 diff 后的,所以傳遞的數(shù)據(jù)更少。
import store from '../../store'
import create from '../../utils/create'
const app = getApp()
create(store, {
onLoad: function () {
if (app.globalData.userInfo) {
this.store.data.userInfo = app.globalData.userInfo
this.store.data.hasUserInfo = true
this.update()
} else if (this.data.canIUse) {
app.userInfoReadyCallback = res => {
this.store.data.userInfo = res.userInfo
this.store.data.hasUserInfo = true
this.update()
}
} else {
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.store.data.userInfo = res.userInfo
this.store.data.hasUserInfo = true
this.update()
}
})
}
}
})
綁定數(shù)據(jù)
和以前的寫法沒有差別,直接把 store.data 作為綁定數(shù)據(jù)源。
創(chuàng)建組件
和創(chuàng)建 Page 不一樣的是,創(chuàng)建組件只需傳入一個參數(shù),不需要傳入 store,因為已經從根節(jié)點注入了。
import create from '../../utils/create'
create({
ready: function () {
//you can use this.store here
},
methods: {
//you can use this.store here
}
})
跨頁面同步數(shù)據(jù)
使用 westore 你不用關心跨頁數(shù)據(jù)同步,你只需要專注 this.store.data 便可,修改完在任意地方調用 update 便可
感覺使用是不是很簡單并且this.update 比原生 setData 的性能更優(yōu),更加智能。
westore庫作者GitHub地址:https://github.com/dntzhang/westore