Vue3状态管理进阶:5个Pinia高效使用技巧
1. 基础Store创建
创建用户状态Store:
// stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
id: null,
name: '',
email: '',
isLoggedIn: false
}),
actions: {
login(userData) {
this.id = userData.id
this.name = userData.name
this.email = userData.email
this.isLoggedIn = true
},
logout() {
this.$reset()
}
},
getters: {
username: (state) => state.name || '游客'
}
})
2. 组合式Store
使用setup语法重构:
// stores/products.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'
export const useProductsStore = defineStore('products', () => {
const products = ref([])
const loading = ref(false)
const featuredProducts = computed(() =>
products.value.filter(p => p.featured)
)
async function fetchProducts() {
loading.value = true
products.value = await api.getProducts()
loading.value = false
}
return { products, loading, featuredProducts, fetchProducts }
})
3. Store组合使用
跨Store状态交互:
// stores/cart.js
import { defineStore } from 'pinia'
import { useUserStore } from './user'
export const useCartStore = defineStore('cart', {
state: () => ({
items: []
}),
actions: {
addItem(product) {
const userStore = useUserStore()
if (!userStore.isLoggedIn) {
throw new Error('请先登录')
}
// 添加商品逻辑
}
}
})
4. 持久化状态
实现状态本地存储:
// main.js
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
// Store中使用
export const useUserStore = defineStore('user', {
persist: true,
// ...其他配置
})
特性 | Vuex | Pinia |
---|---|---|
API设计 | 复杂 | 简洁 |
TypeScript支持 | 有限 | 完善 |
模块化 | 需要命名空间 | 自动支持 |
5. 服务端渲染(SSR)支持
Nuxt.js中集成Pinia:
// nuxt.config.js
export default {
modules: [
'@pinia/nuxt',
],
pinia: {
autoImports: [
'defineStore',
['defineStore', 'definePiniaStore']
]
}
}
// 使用示例
import { useCartStore } from '~/stores/cart'
export default {
setup() {
const cart = useCartStore()
return { cart }
}
}
Pinia为Vue3应用提供了现代化、类型安全的状态管理方案,特别适合大型企业级应用开发。