国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

weex里Vuex state使用storage持久化詳解

2019-11-19 15:30:13
字體:
來源:轉載
供稿:網友

在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(_ => _)  } }}) 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁国市| 招远市| 蒲城县| 彩票| 西平县| 区。| 清丰县| 阳新县| 桑日县| 邳州市| 通道| 南雄市| 旌德县| 三台县| 海门市| 武邑县| 德庆县| 汉寿县| 化州市| 徐州市| 志丹县| 商城县| 襄汾县| 方城县| 神池县| 上思县| 花莲市| 阳信县| 松阳县| 宁乡县| 清徐县| 南和县| 龙江县| 乌兰县| 晋中市| 白水县| 贡山| 武平县| 尼勒克县| 雅江县| 车险|