Logo
首页
前沿
AI热点新闻
36氦头条
博客
开源
极简简历
极简智库
瞬间
相册
友链
知识库
创作者
搜索文章 Ctrl K

Pinia 官方文档(中文版)

返回 0
  • 导读
  • 介绍
    • Pinia-是什么
    • 开始
  • 核心概念
    • 定义-Store
    • State
    • Getter
    • Action
    • 插件
    • 组件外的-Store
  • 服务端渲染-SSR
    • Vue-与-Vite
    • Nuxt
  • 手册
    • 目录
    • 从-Vuex-≤4-迁移
    • 热更新
    • 测试
    • 不使用-setup-的用法
    • 组合式-Stores
    • VSCode-代码片段
    • 从-v0-v1-迁移至-v2
    • 处理组合式函数
  • API-参考
    • API-索引

组合式 Store

组合式 store 是可以相互使用,Pinia 当然也支持它。但有一个规则需要遵循:

如果两个或更多的 store 相互使用,它们不可以通过 getters 或 actions 创建一个无限循环。它们也不可以同时在它们的 setup 函数中直接互相读取对方的 state:

const useX = defineStore('x', () => {
  const y = useY()

  // ❌ 这是不可以的,因为 y 也试图读取 x.name
  y.name

  function doSomething() {
    // ✅ 读取 computed 或 action 中的 y 属性
    const yName = y.name
    // ...
  }

  return {
    name: ref('I am X'),
  }
})

const useY = defineStore('y', () => {
  const x = useX()

  // ❌ 这是不可以的,因为 x 也试图读取 y.name
  x.name

  function doSomething() {
    // ✅ 读取 computed 或 action 中的 x 属性
    const xName = x.name
    // ...
  }

  return {
    name: ref('I am Y'),
  }
})

嵌套 store

注意,如果一个 store 使用另一个 store,你可以直接导入并在 actions 和 getters 中调用 useStore() 函数。然后你就可以像在 Vue 组件中那样使用 store。参考共享 Getter 和共享 Action。

对于 setup store ,你直接使用 store 函数顶部的一个 store:

import { useUserStore } from './user'

export const useCartStore = defineStore('cart', () => {
  const user = useUserStore()
  const list = ref([])

  const summary = computed(() => {
    return `Hi ${user.name}, you have ${list.value.length} items in your cart. It costs ${price.value}.`
  })

  function purchase() {
    return apiPurchase(user.id, this.list)
  }

  return { summary, purchase }
})

共享 Getter

你可以直接在一个 getter 中调用 useUserStore():

import { defineStore } from 'pinia'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', {
  getters: {
    summary(state) {
      const user = useUserStore()

      return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.`
    },
  },
})

共享 Actions

actions 也一样:

import { defineStore } from 'pinia'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', {
  actions: {
    async orderCart() {
      const user = useUserStore()

      try {
        await apiOrderCart(user.token, this.items)
        // 其他 action
        this.emptyCart()
      } catch (err) {
        displayError(err)
      }
    },
  },
})
目录
    共 26 篇 Pinia 官方文档(中文版) / 组合式-Stores 0 字 0 行 cosolar
    创建 2026-11-08T09:54:41.982677793Z 更新 2026-11-08T09:57:36.538453037Z
    Logo

    以极简为笔,以求索为墨。 简单书写,深度思考,每一次记录,都是与内心的对话。

    30,291 访问量
    219 点赞数
    0 评论数
    162 文章数 13 分类数 243 标签数
    2026-06-06 建站时间
    中国·北京 博主地址

    订阅更新

    订阅我们的技术文章,每周精选内容送达你的邮箱

    隐私政策 | 使用条款 | 友情链接 | 关于我们
    本主题由 腾讯云 提供云服务
    © 极简笔记 版权所有 津ICP备2026156702号-1
    Powered by Halo Theme halo-theme-cosolar