前言
Pinia 是一个用于 Vue 的状态管理库,类似 Vuex。pinia 是下一代的,更符合直觉的 Vue.js 状态管理库。本文是一个 pinia 用法速查表,用于快速上手 pinia 的用法。
为你的应用初始化pinia
src/main.js
import { createPinia } from 'pinia'
createApp(App).use(createPinia()).mount('#app')
定义一个 pinia store
src/stores/ProductStore.js
import { defineStore } from 'pinia'
// 名称 product 必须是唯一的
export const useProductStore = defineStore('product', {
// 初始化 state
state: () => ({
products: []
}),
getters: {
// getter可以通过参数访问状态
productCount(state) {
return state.products.length
},
productsCheaperThan(state) {
// getter可以接受参数,但是它必须返回一个函数
return (price) => (
state.products.filter(product =>
product.price < price
)
)
}
},
// 用 action 改变 state
actions: {
addProduct(product) {
// 使用 this 访问 state
this.products.push(product)
}
}
})
使用 store (组合式API)
src/App.vue
<script setup>
import { useProductStore } from './stores/ProductStore'
// 创建一个 store 实例
const store = useProductStore()
</script>
<template>
<ul>
<!-- 直接访问 state -->
<li v-for="product in store.products">
...
</li>
</ul>
<!-- 使用 getter -->
<p>{{ store.productCount }}</p>
<ul>
<!-- 使用带参数的 getter -->
<li v-for="product in store.productsCheaperThan(10)">
...
</li>
</ul>
<!-- 使用 action -->
<button @click="store.addProduct(product)">Add</button>
</template>
使用 store (选项式API)
<script setup>
import { useProductStore } from './stores/ProductStore'
// 引入 mapStore 方法
import { mapStores } from 'pinia'
export default {
computed: {
// 映射 store 为计算属性
...mapStores(useProductStore)
}
}
</script>
<template>
<ul>
<!-- productStore 是这个store 的唯一名称,他是由 mapStores方法创建的,创建规则是 “product” + “Store”. -->
<li v-for="product in productStore.products">...</li>
</ul>
<p>{{ productStore.productCount }}</p>
<ul>
<li v-for="product in productStore.productsCheaperThan(10)">...</li>
</ul>
<button @click="productStore.addProduct()">Add</button>
</template>
不使用action 更改 state
// 单个修改
store.x = 1
// 批量修改多个
store.$patch({ x: 1, y: 2})
// 另一种语法
store.$patch(state => {
state.x = 1
state.y = 2
})
// 修改整个 state (替换)
store.$state = { x: 1, y: 2, z: 3 }
// 将整个 state 更改回初始值(重置)
store.$reset()
订阅更改
store.$subscribe((mutation, state) => {
// state: 更改后的 state
// mutation: 有关本次更改的详细信息
})