uniapp中Vuex状态持久化的两种实现方案

作者:南栀

时间:2026-10-30

浏览:131

本文介绍了在uniapp项目中实现Vuex状态持久化的两种常用方式。第一种是通过安装vuex-persistedstate插件,配置reduce、paths等参数实现自动持久化;第二种则是手动结合uni.getStorageSync和uni.setStorageSync进行本地存储操作。文章提供了具体的代码示例和配置说明,帮助开发者解决页面刷新后状态丢失的问题。

文章目录

准备工作

在项目的根目录下新建一个名为store的文件夹,并在该文件夹内创建index.js文件作为状态管理的入口。

一、使用插件实现持久化

相关插件的npm地址为:vuex-persistedstate - npm

1. 安装插件

具体代码示例如下:

npm install --save vuex-persistedstate

2. 配置index.js文件:

import api from '@/static/api/index.js' // 引入接口
import createPersistedState from 'vuex-persistedstate' // 引入数据持久化插件
import Vue from 'vue' // 导入vue包
import Vuex from 'vuex' // 导入vuex包
Vue.use(Vuex); // vue的插件机制使用vuex
 
 
// 创建Vuex:构造函数创建store常量
const store = new Vuex.Store({
	// state:提供唯一的公共数据源,所有共享的数据都要统一放到store中的state存储
	state: {
		// 持久化常用参数
		token: uni.getStorageSync('vuex').token, // token
		userId: uni.getStorageSync('vuex').userId, // 用户id
	},
 
 
	// mutations 同步变更state数据,传多个参数需要用对象的方式
	mutations: {
		// 保存TOKEN
		SET_TOKEN: (state, token) => {
			state.token = token
		},
 
		// 保存用户ID
		SET_ID: (state, id) => {
			state.userId = id
		},
 
		// 定义全局的清理方法
		RESET_ALL_STATE(state) {
			state.token = '';
			state.userId = '';
		},
	},
 
	// actions 异步变更state数据
	actions: {
		// 登陆,持久化存储token,id
		loginApi(context, data) {
			return new Promise((resolve, reject) => {
				api.userLogin(data).then(res => {
					const {
						token,
						user_id,
					} = res.data
 
					context.commit('SET_ID', id)
                    context.commit('SET_TOKEN', token)  
				}).catch(err => {
					reject(err)
				})
			})
		},
 
 
		// 退出登陆清空state
		logout(context) {
			return new Promise((resolve, reject) => {
				context.commit('RESET_ALL_STATE')
			})
		}
	},
 
 
	// getters 用于对store中的已有数据进行加工处理形成新的数据,如果store中的数据发生变化,
	getters: {},
 
	// plugins 插件配置
	plugins: [
		createPersistedState({
			paths: ['token', 'userId'],
			storage: { // 存储方式定义  
				getItem: (key) => uni.getStorageSync(key), // 获取  
				setItem: (key, value) => uni.setStorageSync(key, value), // 存储  
				removeItem: (key) => uni.removeStorageSync(key) // 删除  
			}
		})
	]
})
 
export default store

以下是该插件API的主要参数说明:

  • key:用于指定存储持久化状态的键名,默认为vuex。
  • reduce:用于指定存储持久化状态的键,默认为vuex。
  • paths:一个数组,包含需要持久化的状态路径。若未指定路径,则持久化完整状态,默认为空数组[]。
  • reducer:一个函数,用于根据给定的路径对状态进行持久化处理,默认包含这些值。
  • subscriber:一个用于设置突变订阅的函数,默认为store => handler => store.subscribe(handler)。
  • storage:指定存储介质,默认为localStorage,也可替代getState和setState。
  • getState:一个函数,用于重新水化之前持久化的状态,默认使用storage。
  • setState:一个函数,用于将给定状态保持到存储中,默认使用storage。
  • filter:一个函数,用于过滤将触发setState的突变,默认为() => true。

3. 在登录页获取持久化数据:

login() {
    this.$store.dispatch('loginApi', data).then(res => {
		uni.reLaunch({
			url: '/pages/index/index'
		});
	})
}

4. 在个人主页等页面使用state:

<template>
	<view>
		<text>{{id}}</text> 
	</view>
</template>
<script>
	import {mapState} from 'vuex'
	export default {
		data() {
			return {}
		},
		computed: {
			...mapState(["id"),
		},
	}
</script>

二、通过本地存储实现持久化

具体代码示例如下:

import api from '@/static/api/index.js' // 引入接口
import createPersistedState from 'vuex-persistedstate' // 引入数据持久化插件
import Vue from 'vue' // 导入vue包
import Vuex from 'vuex' // 导入vuex包
Vue.use(Vuex); // vue的插件机制使用vuex
 
const store = new Vuex.Store({
	// state:提供唯一的公共数据源,所有共享的数据都要统一放到store中的state存储
	state: {
		// 持久化
		test: uni.getStorageSync('test'),
	},
 
 
	// mutations 同步变更state数据,传多个参数需要用对象的方式
	mutations: {
        // 也可以用 JSON.parse(JSON.stringify(test))
		SET_TEST: (state, test) => {
			state.test = test
			uni.setStorageSync('test', state.test)
		}
	},
 
	// actions 异步变更state数据
	actions: {
		// 持久化实现
		getTest(context, test) {
			context.commit('SET_TEST', test)
		}
	},
 
 
	// getters 用于对store中的已有数据进行加工处理形成新的数据,如果store中的数据发生变化,
	getters: {}
})
 
export default store

总结

本文简要介绍了Vuex持久化的两种实现方式:使用插件或手动进行本地缓存处理。

至此,关于在uniapp中使用Vuex并实现持久化的介绍已完成。如需了解更多相关内容,建议查阅本站过往文章或继续浏览后续文章,感谢大家的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章