weex里Vuex state使用storage持久化詳解
在weex里使用Vuex作為state管理工具,問題來了,如何使得state可以持久化呢?weex官方提供store模塊,因此我們可以嘗試使用該模塊來持久化state。
先看下該模塊介紹:
storage 是一個(gè)在前端比較常用的模塊,可以對(duì)本地?cái)?shù)據(jù)進(jìn)行存儲(chǔ)、修改、刪除,并且該數(shù)據(jù)是永久保存的,除非手動(dòng)清除或者代碼清除。但是,storage 模塊有一個(gè)限制就是瀏覽器端(H5)只能存儲(chǔ)小于5M的數(shù)據(jù),因?yàn)樵?H5/Web 端的實(shí)現(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:[] } }
初始化時(shí),從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)鍵來了,如何存儲(chǔ)?Vuex提供了插件機(jī)制,我們可以通過插件訂閱state的每一次更改,在更改的時(shí)候保存我們感興趣的就OK了
// 存儲(chǔ)plugin,存儲(chǔ)感興趣的數(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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于vue+echarts數(shù)據(jù)可視化大屏展示的實(shí)現(xiàn)
這篇文章主要介紹了基于vue+echarts數(shù)據(jù)可視化大屏展示的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12關(guān)于引入vue.js 文件的知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家分享的是關(guān)于引入vue.js 文件的知識(shí)點(diǎn)總結(jié),有需要的朋友們可以參考學(xué)習(xí)下。2020-01-01vuex直接修改state、commit和dispatch修改state的用法及區(qū)別說明
這篇文章主要介紹了vuex直接修改state、commit和dispatch修改state的用法及區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08vue項(xiàng)目打包之后生成一個(gè)可修改IP地址的文件(具體操作)
這篇文章主要介紹了vue項(xiàng)目打包之后生成一個(gè)可修改IP地址的文件(具體操作),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03