uniapp vue3 使用 pinia

javascript 复制代码
npm i pinia
npm install pinia pinia-plugin-persistedstate
javascript 复制代码
// main.js
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

export function createApp() {
	const app = createSSRApp(App)
	const pinia = createPinia()
	pinia.use(piniaPluginPersistedstate)
	app.use(pinia)
	return {
		app
	}
}

持久化:

javascript 复制代码
import {
	ref
} from 'vue';
import {
	defineStore
} from 'pinia';

export const useAuthStore = defineStore('auth', () => {
	const avatar = ref('');
	const mobile = ref('');
	const name = ref('');
	const token = ref('');

	const login = (userData) => {
		avatar.value = userData.avatar;
		mobile.value = userData.mobile;
		name.value = userData.name;
		token.value = userData.token;
	}

	return {
		avatar,
		mobile,
		name,
		token,
		login
	}
}, {
	persist: {
		key: 'userInfo',
		storage: {
			getItem: (key) => uni.getStorageSync(key),
			setItem: (key, value) => uni.setStorageSync(key, value),
		},
		paths: ['avatar', 'mobile', 'name', 'token'] // 明确指定要缓存的字段
	}
})

组件中使用:

javascript 复制代码
import { useAuthStore } from '@/stores/useAuthStore';

// 缓存用户登录信息
const userInfo = {
	avatar: member_head,
	mobile: member_mobile,
	name: member_name,
	token: member_token
}
const authStore = useAuthStore()
authStore.login(userInfo)
相关推荐
HYI6 分钟前
「三年了,今晚突然开窍!」 一个拖拽排序的顿悟时刻
javascript·vue.js
pepedd86413 分钟前
数组字符串方法有哪些-带你重温js基础
前端·javascript·trae
pepedd86414 分钟前
深入理解js作用域-你真的懂js吗
前端·javascript·trae
日月晨曦30 分钟前
JS闭包:变量的"守护者"与"储物间"
前端·javascript
FFF-X1 小时前
Vue3 路由缓存实战:从基础到进阶的完整指南
vue.js·spring boot·缓存
PineappleCoder1 小时前
为什么说发布 - 订阅是代码的 “万能胶水”?解耦逻辑全解析
前端·javascript·算法
言兴1 小时前
面试题深度解析:localStorage、sessionStorage 与 Cookie —— 前端存储的三大基石
前端·javascript·面试
言兴1 小时前
HTTP 各版本演进史:从文本传输到极致性能 —— 深度解析协议进化与工程实践
前端·javascript·面试
临期程序员1 小时前
TypeError: crypto.getRandomValues is not a function
前端·vue.js