0%

Pinia 替代 Vuex

Pinia 是什么?

Pinia 是 Vue 官方推荐的状态管理库,旨在替代 Vuex。它更轻量,TypeScript 支持更好。

安装

1
npm install pinia

创建 Store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { defineStore } from 'pinia'

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

在组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double: {{ counter.doubleCount }}</p>
<button @click="counter.increment()">+</button>
</div>
</template>

<script>
import { useCounterStore } from '@/stores/counter'

export default {
setup() {
const counter = useCounterStore()

return { counter }
}
}
</script>

异步 Actions

1
2
3
4
5
6
actions: {
async fetchUser() {
const user = await fetch('/api/user')
this.user = await user.json()
}
}

插件

1
2
3
4
5
pinia.use(({ store }) => {
store.$subscribe((mutation, state) => {
// 响应状态变化
})
})

与 Vuex 的比较

  • Pinia 更轻量
  • 更好的 TypeScript 支持
  • 组合式 API 友好
  • 自动代码分割

总结

Pinia 是 Vue 3 时代的首选状态管理。语法简洁,功能强大。迁移 Vuex 项目也很容易。