官方文档

# 安装

yarn add pinia
npm install pinia

创建一个 pinia 实例 (根 store) 并将其传递给应用:

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

# 基础示例

// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // 也可以这样定义
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})

组件中使用该 store :

<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore ()
counter.count++
counter.$patch ({ count: counter.count + 1 })
// 或使用 action 代替
counter.increment ()
</script>
<template>
  <!-- 直接从 store 中访问 state -->
  <div>Current Count: </div>
</template>

使用函数定义 Store (与组件  setup()  类似)

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }
  return { count, increment }
})

类似 Vuex 使用

const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})
const useUserStore = defineStore('user', {
  // ...
})
export default defineComponent({
  computed: {
    // 其他计算属性
    // ...
    // 允许访问 this.counterStore 和 this.userStore
    ...mapStores(useCounterStore, useUserStore)
    // 允许读取 this.count 和 this.double
    ...mapState(useCounterStore, ['count', 'double']),
  },
  methods: {
    // 允许读取 this.increment ()
    ...mapActions(useCounterStore, ['increment']),
  },
})

# 核心概念

# 定义 Store

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

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

# Option Store

与 Vue 的选项式 API 类似,我们也可以传入一个带有  stateactions  与  getters  属性的 Option 对象

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

你可以认为  state  是 store 的数据 ( data ), getters  是 store 的计算属性 ( computed ),而  actions  则是方法 ( methods )。

# Setup Store

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }
  return { count, increment }
})

在 Setup Store 中:

  • ref()  就是  state  属性
  • computed()  就是  getters
  • function()  就是  actions

# 使用 Store

store  是一个用  reactive  包装的对象,这意味着不需要在 getters 后面写  .value

为了从 store 中提取属性时保持其响应性,你需要使用  storeToRefs()

action 可以直接解构

<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia';
const store = useCounterStore ()
// ❌ 这将不起作用,因为它破坏了响应性
// 这就和直接解构 `props` 一样
const { name, doubleCount } = store
name // 将始终是 "Eduardo"
doubleCount // 将始终是 0
setTimeout (() => {
  store.increment ()
}, 1000)
// ✅ 这样写是响应式的
// 💡 当然你也可以直接使用 `store.doubleCount`
const doubleValue = computed (() => store.doubleCount)
// `name` 和 `doubleCount` 是响应式的 ref 
// 同时通过插件添加的属性也会被提取为 ref 
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性 
const { name, doubleCount } = storeToRefs (store) 
// 作为 action 的 increment 可以直接解构 
const { increment } = store
</script>

# State

# 访问 state

const store = useStore()
store.count++

# 重置 state

使用选项式 API 时,你可以通过调用 store 的  $reset()  方法将 state 重置为初始值。

const store = useStore()
store.$reset()

在 Setup Stores 中,需要创建自己的  $reset()  方法

# 变更 state

store.count++
store.$patch({
  count: store.count + 1,
  age: 120,
  name: 'DIO',
})
store.$patch((state) => {
  state.items.push({ name: 'shoes', quantity: 1 })
  state.hasChanged = true
})

# 替换 state

通过变更  pinia  实例的  state  来设置整个应用的初始 state

pinia.state.value = {}

# 订阅 state

类似于 Vuex 的 subscribe 方法,你可以通过 store 的  $subscribe()  方法侦听 state 及其变化。比起普通的  watch() ,使用  $subscribe()  的好处是 subscriptions 在 patch 后只触发一次

cartStore.$subscribe((mutation, state) => {
  // import { MutationType } from 'pinia'
  mutation.type // 'direct' | 'patch object' | 'patch function'
  // 和 cartStore.$id 一样
  mutation.storeId // 'cart'
  // 只有 mutation.type === 'patch object' 的情况下才可用
  mutation.payload // 传递给 cartStore.$patch () 的补丁对象。
  // 每当状态发生变化时,将整个 state 持久化到本地存储。
  localStorage.setItem('cart', JSON.stringify(state))
})

默认情况下,state subscription 会被绑定到添加它们的组件上 (如果 store 在组件的  setup()  里面)。这意味着,当该组件被卸载时,它们将被自动删除。如果你想在组件卸载后依旧保留它们,请将  { detached: true }  作为第二个参数,以将 state subscription 从当前组件中分离:

<script setup>
const someStore = useSomeStore()
// 此订阅器即便在组件卸载之后仍会被保留
someStore.$subscribe(callback, { detached: true })
</script>

# 在组件外使用 store

import { createRouter } from 'vue-router'
const router = createRouter({
  // ...
})
// ❌ 由于引入顺序的问题,这将失败
const store = useStore()
router.beforeEach((to, from, next) => {
  // 我们想要在这里使用 store
  if (store.isLoggedIn) next()
  else next('/login')
})
router.beforeEach((to) => {
  // ✅ 这样做是可行的,因为路由器是在其被安装之后开始导航的,
  // 而此时 Pinia 也已经被安装。
  const store = useStore()
  if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
})