在weex里使用Vuex作為state管理工具,問題來了,如何使得state可以持久化呢?weex官方提供store模塊,因此我們可以嘗試使用該模塊來持久化state。
先看下該模塊介紹:
storage 是一個在前端比較常用的模塊,可以對本地數據進行存儲、修改、刪除,並且該數據是永久保存的,除非手動清除或者代碼清除。但是,storage 模塊有一個限制就是瀏覽器端(H5)只能存儲小於5M的數據,因為在 H5/Web 端的實現是采用 HTML5 LocalStorage API。而 Android 和 iOS 這塊是沒什么限制的。
首先,引入模塊:
const storage = weex.requireModule('storage')
定義state
var state = {
banner:[],
activeTabIndex:0,
lists: {
searchList:[],
tabColumns: {
new:[],
hot:[],
select:[]
},
items:[]
}
}
初始化時,從storage加載state數據
// 從storage里加載數據
storage.getItem(STORAGE_KEY, event => {
if (event.result == "success" && event.data){
// 這里可以使用extend等方法,這里僅舉例說明
var data = JSON.parse(event.data);
state.banner = data.banner;
state.activeTabIndex = data.activeTabIndex;
}
})
關鍵來了,如何存儲?Vuex提供了插件機制,我們可以通過插件訂閱state的每一次更改,在更改的時候保存我們感興趣的就OK了
// 存儲plugin,存儲感興趣的數據,store里數據太多,沒必要全持久化
const storagePlugin = store => {
store.subscribe((mutation, {activeTabIndex,banner}) => {
storage.setItem(STORAGE_KEY, JSON.stringify({activeTabIndex,banner}),event => {
console.log('cache success');
})
})
}
最后,創建Vuex,大功告成
const store = new Vuex.Store({
actions,
mutations,
plugins:[storagePlugin],
state: state,
getters: {
// ids of the items that should be currently displayed based on
// current list type and current pagination
activeIds (state) {
const { activeType, lists, counts } = state
return activeType ? lists[activeType].slice(0, counts[activeType]) : []
},
// items that should be currently displayed.
// this Array may not be fully fetched.
activeItems (state, getters) {
return getters.activeIds.map(id => state.items[id]).filter(_ => _)
}
}
})
