uniapp vue3 store如何使用

在uniapp中使用vue3的store时遇到一些问题,具体配置如下:

  1. 已经按照官方文档创建了store,但在页面中无法获取到state数据
  2. 使用getters时返回undefined
  3. 在setup语法中如何正确使用mapState和mapGetters
  4. 组件中调用action方法时报错"store is not defined"
  5. 如何在uniapp中持久化存储vuex的状态数据

请问正确的使用姿势是什么?能否提供一个完整的示例代码?

2 回复

在uniapp中使用vue3的store,需先安装pinia。创建store文件,定义state、getters、actions。在main.js中引入并挂载。组件中通过useStore()使用。


在 UniApp + Vue 3 中使用状态管理(Store),推荐使用 Pinia(官方推荐替代 Vuex 的轻量级方案)。以下是具体步骤:

1. 安装 Pinia

npm install pinia

2. 创建 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
  }
})

3. 配置 main.js

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')

4. 在组件中使用

<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

在 store 中配置:

export const useCounterStore = defineStore('counter', {
  // ... 其他配置
  persist: {
    enabled: true,
    strategies: [
      { storage: localStorage } // 或 uni.setStorageSync
    ]
  }
})

特点说明:

  • 响应式:直接修改 state 或通过 actions 修改
  • 模块化:每个 store 独立管理
  • TypeScript:天然支持类型推断
  • 轻量:比 Vuex 更简洁的 API

通过以上步骤即可在 UniApp 中快速实现状态管理。注意在 H5/小程序等平台使用时,需确保存储方案兼容对应平台 API。

回到顶部