UniApp状态管理终极方案:Pinia在跨平台开发中的实战应用
1. Pinia基础集成
在UniApp中配置Pinia:
// store/index.js
import { createPinia } from 'pinia'
import { createUnistore } from '@uni-helper/pinia-plugin-unistore'
const pinia = createPinia()
pinia.use(createUnistore())
export default pinia
// main.js
import { createSSRApp } from 'vue'
import pinia from './store'
import App from './App.vue'
export function createApp() {
const app = createSSRApp(App)
app.use(pinia)
return { app }
}
2. 用户状态管理实战
创建用户Store实现登录状态共享:
// store/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { uniStorage } from '@/utils/uni-storage'
export const useUserStore = defineStore('user', () => {
const token = ref(uniStorage.get('token') || ''
const userInfo = ref(uniStorage.get('userInfo') || null
const login = async (credentials) => {
const res = await uni.login(credentials)
token.value = res.token
userInfo.value = res.user
uniStorage.set('token', res.token)
uniStorage.set('userInfo', res.user)
}
const logout = () => {
token.value = ''
userInfo.value = null
uniStorage.remove('token')
uniStorage.remove('userInfo')
}
return { token, userInfo, login, logout }
})
3. 购物车状态管理
实现多端同步的购物车功能:
// store/cart.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useCartStore = defineStore('cart', () => {
const items = ref([])
const total = computed(() => items.value.reduce((sum, item) => {
return sum + (item.price * item.quantity)
}, 0))
const addItem = (product) => {
const existing = items.value.find(i => i.id === product.id)
if (existing) {
existing.quantity++
} else {
items.value.push({ ...product, quantity: 1 })
}
syncToStorage()
}
const syncToStorage = () => {
uni.setStorageSync('cart', JSON.stringify(items.value))
}
// 初始化从存储加载
const initFromStorage = () => {
const data = uni.getStorageSync('cart')
if (data) items.value = JSON.parse(data)
}
return { items, total, addItem, initFromStorage }
})
4. 多端数据同步方案
使用Pinia插件实现小程序数据同步:
// plugins/sync.js
export const createSyncPlugin = () => {
return ({ store }) => {
// 监听状态变化同步到storage
store.$subscribe((mutation, state) => {
uni.setStorageSync(store.$id, JSON.stringify(state))
})
// 从storage初始化状态
const data = uni.getStorageSync(store.$id)
if (data) {
store.$patch(JSON.parse(data))
}
}
}
// store/index.js中注册插件
pinia.use(createSyncPlugin())
方案 | 优点 | 适用场景 |
---|---|---|
Pinia | 轻量、TypeScript支持 | 中大型项目 |
Vuex | 成熟、社区支持 | 传统项目 |
本地存储 | 简单直接 | 简单数据持久化 |
5. 性能优化与调试
提升Pinia在UniApp中的性能:
// 1. 按需导入Store
const userStore = useUserStore()
// 2. 使用storeToRefs避免响应式丢失
import { storeToRefs } from 'pinia'
const { token, userInfo } = storeToRefs(userStore)
// 3. 开发环境调试工具配置
if (process.env.NODE_ENV === 'development') {
pinia.use(({ store }) => {
store.$onAction(({ name, args }) => {
console.log(`Action ${name} with args`, args)
})
})
}
通过合理使用Pinia进行状态管理,可以显著提升UniApp项目的开发效率和跨平台一致性,特别适合复杂的商业应用开发。