来源
Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
Pinia (发音为 /piːnjʌ/,类似英文中的 “peenya”) 是最接近有效包名 piña (西班牙语中的 pineapple,即“菠萝”) 的词
优点
Devtools 支持
追踪 actions、mutations 的时间线
在组件中展示它们所用到的 Store
让调试更容易的 Time travel
热更新
不必重载页面即可修改 Store
开发时可保持当前的 State
插件:可通过插件扩展 Pinia 功能
为 JS 开发者提供适当的 TypeScript 支持以及自动补全功能。
支持服务端渲染
基本的使用
在store/counter.js中使用
import {ref} from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0) //定义状态 count
function increment() { // 定义改变状态的方法
count.value++
}
// 导出状态与方法
return { count, increment }
})
在main.js中引入
import { createPinia } from 'pinia'
app.use(createPinia())
在组件中使用
// 导入仓库
import { useCounterStore } from '@/stores/counter'
// 生成仓库
const counter = useCounterStore()
// 更新仓库
counter.count++
counter.increment()
用调用 $patch 方法 更改state中数据
store.$patch({
count: store.count + 1,
age: 120,
})
store.$patch((state) => {
state.items.push({ name: 'shoes', quantity: 1 })
state.hasChanged = true
})
State-监听(存储到本地)
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))
}, { detached: true })
watch(
pinia.state,
(state) => {
// 每当状态发生变化时,将整个 state 持久化到本地存储。
localStorage.setItem('piniaState', JSON.stringify(state))
},
{ deep: true }
)
计算
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
return { count, doubleCount }
})