1. 基础用法
通过 defineStore
定义一个 store,并在其中定义 state
。state
是一个返回初始状态的函数或对象。
// stores/counter.ts
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
// 其他actions等
});
在组件中使用这个 state
:
<template>
<div>
<p>Count: {{ count }}</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useCounterStore } from './stores/counter';
const counterStore = useCounterStore();
const count = ref(counterStore.state.count);
// 当store中的state发生变化时,这里会自动更新
</script>
2. 重置状态
要重置 state
到其初始值,你可以直接调用 store 实例上的 $reset
方法。
// 在某个方法中
counterStore.$reset(); // 这将重置state到其初始值
3. 改变状态
改变 state
非常直接:你可以直接修改其属性。当你修改 state
时,任何依赖于这个 state
的组件都会自动更新。
counterStore.state.count = 10; // 直接修改state的值
如果你需要在单个操作中修改多个 state
属性,建议使用 $patch
方法,这样可以更清晰地表达你的意图,并避免潜在的副作用。
counterStore.$patch({
count: 10,
// 其他属性...
});
4. 订阅状态
你可以使用 watch
函数来订阅 state
的变化。当 state
的值发生变化时,订阅的回调函数将被执行。
import { watch } from 'vue';
watch(
() => counterStore.state.count, // 监听state的变化
(newCount, oldCount) => {
console.log(`Count changed from ${oldCount} to ${newCount}`);
}
);
5. 替换状态
虽然直接修改 state
是最常见的做法,但有时你可能想完全替换当前的 state
。这可以通过将一个新的对象或值分配给 state
来实现。但请注意,这样做会替换整个 state
对象,而不是合并属性。
counterStore.state = { count: 20 }; // 替换整个state对象
通常,更推荐使用
$patch
方法来合并属性,而不是完全替换state
。