uniapp vue3 使用 pinia

发布于:2025-08-15 ⋅ 阅读:(11) ⋅ 点赞:(0)
npm i pinia
npm install pinia pinia-plugin-persistedstate
// 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
	}
}

持久化:

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'] // 明确指定要缓存的字段
	}
})

组件中使用:

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)

网站公告

今日签到

点亮在社区的每一天
去签到