核心概念
约 376 字大约 1 分钟
2025-08-09
Pinia 是 Vue 3 的官方状态管理库,其核心概念包括以下部分:
Store
Store 是一个保存状态和业务逻辑的实体,类似于一个永远存在的组件,每个组件都可以读取和写入它。通过 defineStore()
定义,包含 state
、getters
和 actions
三个核心部分。
State
相当于组件中的 data,用于存储响应式数据。State 是一个函数,返回一个对象,其中包含需要管理的状态。例如:
state: () => ({ count: 0 });
Getter
类似于组件的 computed 属性,用于派生状态。Getter 接收 state 作为参数,返回计算后的值。例如:
getters: {
double: (state) => state.count * 2;
}
Action
相当于组件的 methods,用于封装业务逻辑,支持同步和异步操作。Action 通过 this 访问当前 Store 的 state 和其他方法。例如:
actions: {
increment() {
this.count++;
}
}
标准案例
app.vue
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ doubleCount }}</p>
<button @click="incrementCount()">count ++</button>
<button @click="decrementCount()">count --</button>
</div>
</template>
<script setup>
import { useCounterStore } from "./counterStore";
import { storeToRefs } from "pinia";
const counterStore = useCounterStore();
// 使用 storeToRefs 保持响应式
const { count, doubleCount } = storeToRefs(counterStore);
// 直接解构 actions
const { incrementCount, decrementCount } = counterStore;
</script>
counterStore.ts
// 选项式 API
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
// State 定义
state: () => ({
count: 0,
}),
// Getter 定义
getters: {
doubleCount: (state) => state.count * 2,
},
// Action 定义
actions: {
incrementCount() {
this.count++;
},
decrementCount() {
this.count--;
},
},
});
userStore.ts
// 组合式API
import { ref, computed } from "vue";
import { defineStore } from "pinia";
export const useUserInfoStore = defineStore("userInfo", () => {
const name = ref("kangkang");
const age = ref(18);
function changename() {
name.value += "6";
}
return { name, doubleCount, increment };
});
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于