vuejs3.0 从入门到精通——Pinia——定义Store

发布时间 2023-11-14 15:05:33作者: 左扬

定义Store

  Store 是用defineStore()定义的,它的第一个参数要求是一个独一无二的名字:

import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useAlertsStore = defineStore('alerts', {
  // 其他配置...
})

  这个名字,也被用作id,是必须传入的, Pinia 将用它来连接 store 和 devtools。为了养成习惯性的用法,将返回的函数命名为use...是一个符合组合式函数风格的约定。

  defineStore()的第二个参数可接受两类值:Setup 函数或 Option 对象。