上一篇文章完成了 Pinia 在钉钉小程序中的引入与基础配置
文章地址:钉钉小程序框架引入 Pinia 状态管理-CSDN博客
本文将深入探讨如何通过Pinia 结合持久化存储 实现用户状态
在上一章节中,我们已经完成了 Pinia 在钉钉小程序中的引入与基础配置。本章将进一步深入探讨如何通过 Pinia 结合持久化存储 实现用户状态、应用设置等关键数据的持久保存,并结合实际场景封装一个通用的 持久化工具类。
我们将使用 uni.setStorageSync
和 uni.getStorageSync
这两个钉钉小程序兼容的 API 来实现本地存储,同时借助 Pinia 的 store 模块机制进行统一的状态管理。
一、为什么需要持久化 Pinia Store
在开发钉钉小程序时,有些数据是需要跨页面甚至跨会话保留的,例如:
- 用户登录信息(token、用户ID)
- 应用主题设置
- 缓存数据(如历史记录、最近访问内容)
如果不做持久化处理,当用户关闭小程序后再次打开时,这些状态将会丢失。
二、Pinia + 持久化方案设计
1. 持久化策略概述
我们采用如下策略:
- 在 Pinia 的 store 初始化时从本地缓存读取初始值;
- 在每次状态变更时自动写入本地缓存;
- 提供一个可复用的工具类来统一管理存储逻辑。
2. 技术选型说明
技术点 | 选择理由 |
---|---|
Pinia | Vue3 推荐的状态管理库,类型友好,模块化清晰 |
TypeScript | 强类型支持,提升代码健壮性 |
UniApp API | 使用 uni.setStorageSync 等 API 兼容多端 |
三、封装持久化工具类
1. 我们可以创建一个 utils/storage.ts
工具类用于封装常用的本地存储方法。
/*** 存储工具类* @author: 归梦工作室*/
const STORAGE_PREFIX = 'gm_';export const setStorage = <T>(key: string, value: T): void => {try {uni.setStorageSync(`${STORAGE_PREFIX}${key}`, value);} catch (e) {console.error(`[Storage] Set failed for key ${key}`, e);}
};export const getStorage = <T>(key: string, defaultValue: T | null = null): T | null => {try {const value = uni.getStorageSync(`${STORAGE_PREFIX}${key}`);return value !== undefined ? (value as T) : defaultValue;} catch (e) {console.error(`[Storage] Get failed for key ${key}`, e);return defaultValue;}
};export const removeStorage = (key: string): void => {uni.removeStorageSync(`${STORAGE_PREFIX}${key}`);
};export const clearStorage = (): void => {uni.clearStorageSync();
};
五、Pinia Store 中集成持久化逻辑
1. 创建一个带持久化的 Store 示例
以 userStore
为例:
文件位置:src/store/user.ts
import { defineStore } from 'pinia';
import { getStorage, setStorage } from '@/utils/storage';interface UserState {token: string | null;userInfo: Record<string, any> | null;
}export const useUserStore = defineStore('user', {state: (): UserState => ({token: getStorage<string>('token', null),userInfo: getStorage<Record<string, any>>('userInfo', null),}),actions: {setToken(token: string | null) {this.token = token;if (token) {setStorage('token', token);} else {uni.removeStorageSync('token');}},setUserInfo(userInfo: Record<string, any> | null) {this.userInfo = userInfo;if (userInfo) {setStorage('userInfo', userInfo);} else {uni.removeStorageSync('userInfo');}},},
});
2. 测试持久化存储
<template><view class="content"><view>测试pinia持久化</view><view>vuex: {{ userData }}</view><view>storage: {{ getStorage('userInfo') }}</view></view><view><ant-button @tap="savaToken">存储 token</ant-button><ant-button @tap="savaUserInfo">存储 userInfo</ant-button><ant-button @tap="getUserInfo">获取 userInfo</ant-button><ant-button @tap="clearStorage">清空 storage</ant-button></view>
</template><script setup lang="ts">
import {ref} from 'vue'
import {useUserStore} from "@/store/user";
import { getStorage, clearStorage } from '@/utils/storage';const userStore = useUserStore()const userData = ref({})const userInfo = ref({name: '张三',age: 18
})const token = ref('123456')const savaToken = () => {userStore.setToken(token.value)
}
const savaUserInfo = () => {userStore.setUserInfo(userInfo.value)
}
const getUserInfo = () => {userData.value = userStore.getUserInfo()
}</script><style>
.content {display: flex;flex-direction: column;align-items: center;justify-content: center;
}.logo {height: 200rpx;width: 200rpx;margin-top: 200rpx;margin-left: auto;margin-right: auto;margin-bottom: 50rpx;
}.text-area {display: flex;justify-content: center;
}.title {font-size: 36rpx;color: #8f8f94;
}
</style>
点击存储token和存储userInfo
点击清空storage
最后点击获取userInfo
测试完成!!!一切顺利!!!
最后附上代码地址:
GitCode - 全球开发者的开源社区,开源代码托管平台
分支:storage