
在 Pinia 中定义一个 Store 非常简单。你可以使用 defineStore
函数来创建一个 Store。defineStore
接受两个参数:Store 的名称和一个配置对象(或一个函数,如果使用组合式 API)。以下是定义 Store 的几种常见方式:
1. 使用选项式 API 定义 Store
这是最常见的方式,适合大多数场景。你可以通过 state
、getters
和 actions
来定义 Store 的状态、计算属性和方法。
import { defineStore } from 'pinia';
// 使用选项式 API 定义 Store
export const useCounterStore = defineStore('counter', {
// 定义状态
state: () => ({
count: 0,
}),
// 定义计算属性
getters: {
doubleCount: (state) => state.count * 2,
},
// 定义方法
actions: {
increment() {
this.count++;
},
async incrementAsync() {
setTimeout(() => {
this.increment();
}, 1000);
},
},
});
2. 使用组合式 API 定义 Store
如果你更喜欢 Vue 3 的组合式 API,可以使用函数来定义 Store。这种方式更加灵活,适合复杂逻辑。
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
// 使用组合式 API 定义 Store
export const useCounterStore = defineStore('counter', () => {
// 定义状态
const count = ref(0);
// 定义计算属性
const doubleCount = computed(() => count.value * 2);
// 定义方法
function increment() {
count.value++;
}
async function incrementAsync() {
setTimeout(() => {
increment();
}, 1000);
}
return { count, doubleCount, increment, incrementAsync };
});
3. 在组件中使用 Store
定义好 Store 后,你可以在组件中使用它。通常会在 setup
函数中调用 useStore
来获取 Store 实例。
import { useCounterStore } from '@/stores/counter';
export default {
setup() {
const counterStore = useCounterStore();
return {
counterStore,
};
},
};
4. 访问 State、Getters 和 Actions
在组件中,你可以直接访问 Store 的 state
、getters
和 actions
。
<template>
<div>
<p>Count: {{ counterStore.count }}</p>
<p>Double Count: {{ counterStore.doubleCount }}</p>
<button @click="counterStore.increment">Increment</button>
<button @click="counterStore.incrementAsync">Increment Async</button>
</div>
</template>
<script>
import { useCounterStore } from '@/stores/counter';
export default {
setup() {
const counterStore = useCounterStore();
return {
counterStore,
};
},
};
</script>
总结
在 Pinia 中定义 Store 非常简单,你可以使用选项式 API 或组合式 API 来定义 Store。定义好 Store 后,可以在组件中使用 useStore
来获取 Store 实例,并访问其 state
、getters
和 actions
。Pinia 的设计使得状态管理变得灵活且易于维护。
学在每日,进无止境!更多精彩内容请关注微信公众号。

原文出处:
内容由AI生成仅供参考,请勿使用于商业用途。如若转载请注明原文及出处。
出处地址:http://www.07sucai.com/tech/826.html
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。