Skip to content

Store API(状态管理)

wevu 的 store 设计接近 Pinia:defineStore 定义,createStore 创建管理器,storeToRefs 安全解构。

1. 核心函数

API类型入口说明
defineStoreDefineStoreOptions定义 store(setup/option 两种风格)。
createStoreStoreManager创建 store 管理器(插件、作用域隔离)。
storeToRefsToRefs将 store 状态安全转换为 ref。

2. 常用类型

类型链接用途
StoreManagerStoreManagerstore 根管理器。
DefineStoreOptionsDefineStoreOptions选项式 store 定义类型。
ActionSubscriberActionSubscriberaction 订阅回调签名。
SubscriptionCallbackSubscriptionCallback状态变更订阅回调。
MutationRecordMutationRecordmutation 记录结构。
MutationKindMutationKindmutation 大类。
MutationTypeMutationTypemutation 类型枚举。
MutationOpMutationOpmutation 操作类型。
WevuPluginWevuPluginstore/runtime 插件类型。

3. 端到端示例(script setup)

vue
<script setup lang="ts">
import { computed, createStore, defineStore, ref, storeToRefs } from 'wevu'

// [TS-only] 此示例无专属语法,TS/JS 写法一致。
const storeManager = createStore()

const useCartStore = defineStore('cart', () => {
  const count = ref(0)
  const total = computed(() => count.value * 99)
  function addOne() {
    count.value += 1
  }
  return { count, total, addOne }
})

const cart = useCartStore(storeManager)
const { count, total } = storeToRefs(cart)
</script>

<template>
  <view>count: {{ count }} / total: {{ total }}</view>
  <button @tap="cart.addOne">
    +1
  </button>
</template>
vue
<script setup>
import { computed, createStore, defineStore, ref, storeToRefs } from 'wevu'

const storeManager = createStore()

const useCartStore = defineStore('cart', () => {
  const count = ref(0)
  const total = computed(() => count.value * 99)
  function addOne() {
    count.value += 1
  }
  return { count, total, addOne }
})

const cart = useCartStore(storeManager)
const { count, total } = storeToRefs(cart)
</script>

<template>
  <view>count: {{ count }} / total: {{ total }}</view>
  <button @tap="cart.addOne">
    +1
  </button>
</template>

4. 调试建议

5. 相关页

Released under the MIT License.