在现代 Vue 工程化项目中,通常推荐使用 Pinia(或 Vuex)来管理状态,而不是直接使用 localStorage。我来解释下具体原因和使用方式:
1、为什么使用 Pinia 替代 localStorage:
| |
| - 状态集中管理,更容易维护 |
| - 支持响应式 |
| - 支持开发工具调试 |
| - 支持 TypeScript |
| - 可以配合 localStorage 实现数据持久化 |
| - 状态变更可追踪 |
2、一个典型的用户认证 Store 示例:
| |
| import { defineStore } from 'pinia' |
| |
| export const useAuthStore = defineStore('auth', { |
| state: () => ({ |
| isAuthenticated: false, |
| token: null, |
| user: null |
| }), |
| |
| actions: { |
| login(credentials) { |
| |
| |
| this.isAuthenticated = true; |
| this.token = 'token-value'; |
| |
| localStorage.setItem('token', this.token); |
| }, |
| |
| logout() { |
| this.isAuthenticated = false; |
| this.token = null; |
| this.user = null; |
| localStorage.removeItem('token'); |
| }, |
| |
| |
| initializeAuth() { |
| const token = localStorage.getItem('token'); |
| if (token) { |
| this.token = token; |
| this.isAuthenticated = true; |
| } |
| } |
| }, |
| |
| getters: { |
| |
| isUserLoggedIn: (state) => state.isAuthenticated, |
| currentUser: (state) => state.user |
| } |
| }) |
3、在路由守卫中使用:
| |
| import { useAuthStore } from '@/stores/auth' |
| |
| router.beforeEach((to, from, next) => { |
| const authStore = useAuthStore() |
| |
| |
| if (to.meta.requiresAuth && !authStore.isAuthenticated) { |
| next({ name: 'login' }) |
| } else { |
| next() |
| } |
| }) |
4、在组件中使用:
| <template> |
| <div> |
| <h1>Admin Dashboard</h1> |
| <div v-if="authStore.isUserLoggedIn"> |
| Welcome, {{ authStore.currentUser?.name }} |
| </div> |
| </div> |
| </template> |
| |
| <script setup> |
| import { useAuthStore } from '@/stores/auth' |
| |
| const authStore = useAuthStore() |
| |
| // 组件内使用 |
| const handleLogout = () => { |
| authStore.logout() |
| } |
| </script> |
5、配合插件实现自动持久化(可选):
| |
| import { createPinia } from 'pinia' |
| import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' |
| |
| const pinia = createPinia() |
| pinia.use(piniaPluginPersistedstate) |
| |
| |
| export const useAuthStore = defineStore('auth', { |
| state: () => ({ |
| |
| }), |
| persist: true |
| }) |
6、最佳实践:
| |
| |
| export const authApi = { |
| login: (credentials) => axios.post('/api/login', credentials), |
| logout: () => axios.post('/api/logout') |
| } |
| |
| |
| export const useAuthStore = defineStore('auth', { |
| |
| }) |
| |
| |
| actions: { |
| async login(credentials) { |
| try { |
| const response = await authApi.login(credentials) |
| this.setUser(response.data.user) |
| return Promise.resolve('Success') |
| } catch (error) { |
| return Promise.reject(error) |
| } |
| } |
| } |
| |
| |
| interface User { |
| id: number |
| name: string |
| email: string |
| } |
| |
| interface AuthState { |
| user: User | null |
| isAuthenticated: boolean |
| token: string | null |
| } |
使用 Pinia 的主要好处是:
- 状态管理更规范
- 数据响应式,自动更新视图
- 可以配合 TypeScript 获得更好的类型支持
- 支持开发工具,方便调试
- 可以实现状态持久化
- 便于测试和维护
- 状态变更可追踪,便于调试
当然,在某些简单的场景下,直接使用 localStorage 也是可以的。选择哪种方式主要取决于:
- 项目规模和复杂度
- 团队规模和开发规范
- 是否需要状态响应式
- 是否需要更好的开发体验
- 是否需要类型支持
在中大型项目中,推荐使用 Pinia 来管理状态,可以获得更好的可维护性和开发体验。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗