uniapp中Vuex数据持久化

问题

H5应用中存在Vuex中的数据在刷新页面后丢失了。

原因

Vuex的 store 中的数据是保存在运行内存中的,当页面刷新时,页面会重新加载 Vue 实例,Vuex数据会重新初始化,导致页面刷新Vuex中的数据丢失的问题。

解决方法

使用 vuex-persistedstate 插件

1、在项目目录下执行:npm install --save vuex-persistedstate;
2、修改store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from "vuex-persistedstate"

Vue.use(Vuex)

const store = new Vuex.Store({
    
    
	plugins: [
		persistedState({
    
    
			storage: {
    
    
				getItem: key => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: key => uni.removeStorageSync(key)
			}
		})
	],
	state:{
    
    //存放状态
        "username":'',
        "userid":''
    },
	mutations:{
    
    
		//...
	},
	actions:{
    
    
		//...
	},
	//...
})

export default store

使用后浏览器打开用控制台调试可看数据存放在 window.localStorage.vuex
这里其实就和调用uniapp提供的数据缓存API存放的数据位置一样了,官方文档链接:https://uniapp.dcloud.io/api/storage/storage.html

注意:在APP-PLUS环境下,这个数据在应用退出时默认不会被清空(或者说初始化)。

猜你喜欢

转载自blog.csdn.net/Mr_Bobcp/article/details/125876232
今日推荐