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;
}
})
關(guān)鍵來了,如何存儲?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(_ => _)
}
}
})
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue 實現(xiàn) ios 原生picker 效果及實現(xiàn)思路解析
這篇文章主要介紹了vue 實現(xiàn) ios 原生picker 效果及實現(xiàn)思路解析,本文給大家介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2017-12-12
Vue3.x的版本中build后dist文件中出現(xiàn)legacy的js文件問題
這篇文章主要介紹了Vue3.x的版本中build后dist文件中出現(xiàn)legacy的js文件問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
vue3+ts實際開發(fā)中該如何優(yōu)雅書寫vue3語法
近嘗試上手 Vue3+TS+Vite,所以下面這篇文章主要給大家介紹了關(guān)于vue3+ts實際開發(fā)中該如何優(yōu)雅書寫vue3語法的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-10-10
ant design vue中table表格滾動加載實現(xiàn)思路
在處理一寫數(shù)據(jù)量特別大的情況下,我們不能把后端的數(shù)據(jù)一次性全部拿到前端在table表格中展示,為了考慮性能優(yōu)化,使用了滾動加載表格數(shù)據(jù),這篇文章主要介紹了ant design vue中table表格滾動加載實現(xiàn)思路,需要的朋友可以參考下2024-07-07

