weex里Vuex state使用storage持久化詳解
在weex里使用Vuex作為state管理工具,問題來了,如何使得state可以持久化呢?weex官方提供store模塊,因此我們可以嘗試使用該模塊來持久化state。
先看下該模塊介紹:
storage 是一個在前端比較常用的模塊,可以對本地數(shù)據(jù)進行存儲、修改、刪除,并且該數(shù)據(jù)是永久保存的,除非手動清除或者代碼清除。但是,storage 模塊有一個限制就是瀏覽器端(H5)只能存儲小于5M的數(shù)據(jù),因為在 H5/Web 端的實現(xiàn)是采用 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數(shù)據(jù)
// 從storage里加載數(shù)據(jù)
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,存儲感興趣的數(shù)據(jù),store里數(shù)據(jù)太多,沒必要全持久化
const storagePlugin = store => {
store.subscribe((mutation, {activeTabIndex,banner}) => {
storage.setItem(STORAGE_KEY, JSON.stringify({activeTabIndex,banner}),event => {
console.log('cache success');
})
})
}
最后,創(chuàng)建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(_ => _)
}
}
})
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于vue+echarts數(shù)據(jù)可視化大屏展示的實現(xiàn)
這篇文章主要介紹了基于vue+echarts數(shù)據(jù)可視化大屏展示的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
vuex直接修改state、commit和dispatch修改state的用法及區(qū)別說明
這篇文章主要介紹了vuex直接修改state、commit和dispatch修改state的用法及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

