uniapp 如何使用pinia进行状态管理
“在uniapp中使用pinia进行状态管理时,发现引入store后页面无法获取最新状态值。按照官方文档配置了pinia插件,但在H5和微信小程序端表现不一致:H5正常更新,小程序却始终读取初始值。请问该如何正确跨端同步pinia状态?是否需要针对小程序做特殊处理?另外pinia的持久化存储是否推荐用uni.setStorage同步?”
2 回复
在uniapp中使用pinia:
- 安装:
npm install pinia - main.js中引入:
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
- 创建store:
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
- 页面中使用:
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
// 使用:counter.count, counter.increment()
在 UniApp 中使用 Pinia 进行状态管理,可以高效管理全局状态。以下是详细步骤:
1. 安装依赖
在项目根目录执行:
npm install pinia
2. 配置 Pinia
在 main.js 中引入并创建 Pinia 实例:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
3. 创建 Store
在 stores 目录下创建状态管理文件(例如 counter.js):
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
},
getters: {
doubleCount: (state) => state.count * 2
}
})
4. 在组件中使用
在 Vue 组件中引入并使用 Store:
<template>
<view>
<text>Count: {{ counter.count }}</text>
<text>Double: {{ counter.doubleCount }}</text>
<button @click="counter.increment()">+1</button>
<button @click="counter.decrement()">-1</button>
</view>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
5. 持久化存储(可选)
如需数据持久化,可配合 pinia-plugin-persistedstate:
npm install pinia-plugin-persistedstate
在 main.js 中配置:
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
在 Store 中启用:
export const useCounterStore = defineStore('counter', {
// ... 其他配置
persist: true
})
注意事项:
- 确保 UniApp 项目已配置 Vue 3(Pinia 仅支持 Vue 3)
- Store 状态变更会自动更新相关组件
- 支持 H5 和小程序平台
通过以上步骤即可在 UniApp 中实现 Pinia 状态管理,提高应用的可维护性和开发效率。

