官网:Pinia | The intuitive store for Vue.js
安装:npm install pinia
简介:Pinia 是 Vue 官方推荐的新一代状态管理库,全面替代 Vuex,专为 Vue3 设计,完美适配组合式 API 和 TypeScript,砍掉了冗余的 Mutation,API 极简
挂载
在 main.js/main.ts 中写入
js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const app = createApp(App)
// 创建 Pinia 实例并挂载到 Vue 应用
app.use(createPinia())
app.mount('#app')Store
Store 是一个保存状态和业务逻辑的实体,它并不与组件树绑定。有点像一个永远存在的组件。它有三个概念:
| Store | 等价于Vue | 文档 |
|---|---|---|
| state | data | State |
| getter | computed(计算属性) | Getter |
| action | methods | Action |
Store 是用 defineStore() 定义的,它的第一个参数要求是全局唯一的ID
js
import { defineStore } from 'pinia'
// 第一个参数是应用中 Store 的唯一 ID
export const useAlertsStore = defineStore('alerts', {
// 其他配置...
})Store 函数的命名规范为以 use 开头,以 Store 结尾。如:useAlertsStore
选项式写法
js
export const useCounterStore = defineStore('counter', {
// State: 必须是一个返回对象的箭头函数
state: () => ({
count: 0,
name: 'Eduardo'
}),
// 基于 State 计算属性,等同于 Vue 的 computed
getters: {
doubleCount: (state) => state.count * 2
},
// 等同于 Vue 的 methods (不要用箭头函数,否则会丢失 this 指向)
actions: {
increment() {
this.count++
}
}
})组合式写法
js
export const useCounterStore = defineStore('counter', () => {
// 状态: 计数器和姓名
const count = ref(0)
const name = ref('Eduardo')
// 计算属性: 计算双数
const doubleCount = computed(() => count.value * 2)
// 操作: 增加计数
function increment() {
count.value++
}
// 返回状态、计算属性和操作
return { count, name, doubleCount, increment }
})在组合式写法中:
ref()就是state属性computed()就是gettersfunction()就是actions
使用 Store
在项目根目录下创建一个 stores 文件夹,然后在其中创建 store 文件。如:counter.js
文件中按照 选项式 或者 组合式 写法编写状态管理,然后通过下述代码使用
vue
<script setup>
import { useCounterStore } from '@/stores/counter' // 定义的 Store 存在的位置
// 在组件内部的任何地方均可以访问变量 store
const store = useCounterStore()
</script>