weex里Vuex state使用storage持久化
在weex里使用Vuex作为state管理工具,问题来了,如何使得state可以持久化呢?weex官方提供store模块,因此我们可以尝试使用该模块来持久化state。
先看下该模块介绍:
storage
是一个在前端比较常用的模块,可以对本地数据进行存储、修改、删除,并且该数据是永久保存的,除非手动清除或者代码清除。但是,storage
模块有一个限制就是浏览器端(H5)只能存储小于5M的数据,因为在 H5/Web 端的实现是采用 HTML5 LocalStorage API
。而 Android 和 iOS 这块是没什么限制的。
首先,引入模块:
const storage = weex.requireModule('storage')
定义state
1 2 3 4 5 6 7 8 9 10 11 12 13 | var state = { banner:[], activeTabIndex:0, lists: { searchList:[], tabColumns: { new :[], hot:[], select:[] }, items:[] } } |
初始化时,从storage加载state数据
1 2 3 4 5 6 7 8 9 | // 从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了
1 2 3 4 5 6 7 8 | // 存储plugin,存储感兴趣的数据,store里数据太多,没必要全持久化 const storagePlugin = store => { store.subscribe((mutation, {activeTabIndex,banner}) => { storage.setItem(STORAGE_KEY, JSON.stringify({activeTabIndex,banner}),event => { console.log( 'cache success' ); }) }) } |
最后,创建Vuex,大功告成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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(_ => _) } } }) |
关注作者
作者: JadePeng
出处:https://www.cnblogs.com/xiaoqi/p/weex-Vuex-persistence.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际(欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接) 」知识共享许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2011-03-03 Mediawiki 生成google sitemap
2011-03-03 MySql “找不到请求的 .Net Framework 数据提供程序。可能没有安装。”