在Pinia中,Actions是用于处理异步逻辑和触发mutation的方法。它们相当于组件中的方法,可以处理同步或异步函数,当组件卸载时,如果Action是异步的,并且使用了unref来确保它不会因为组件卸载而被取消,那么订阅会自动被删除。
Actions的介绍
- 处理异步逻辑:Actions是Pinia中处理异步操作(如API调用)的理想场所。你可以在其中执行异步任务,并在完成后更新状态。
- 触发mutation:Actions可以直接修改store的状态,或者通过触发mutation来间接修改状态。这提供了更灵活的状态更新机制。
- 可组合性:Actions可以相互调用,也可以调用其他store的actions或getters,从而实现状态的跨组件、跨页面共享和组合。
Actions的使用
1. 定义Actions
可以使用defineStore函数来定义actions。每个action是一个函数,它可以接受任意参数,并可以在函数体内部修改state或者执行其他逻辑。
import { defineStore } from 'pinia';
export const useMyStore = defineStore({
id: 'myStore',
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
async fetchData() {
const response = await fetch('some-api-url');
const data = await response.json();
this.count = data.someValue;
},
},
});
我们定义了两个actions:increment和fetchData。increment是一个同步action,它直接增加count的值。而fetchData是一个异步action,它使用fetch API从某个URL获取数据,并在获取到数据后更新count的值。
2. 使用Actions
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="incrementCount">Increment</button>
<button @click="fetchData">Fetch Data</button>
</div>
</template>
<script setup lang="ts">
import { useMyStore } from './myStore';
const store = useMyStore();
const count = store.count;
const incrementCount = () => {
store.increment();
};
const fetchData = async () => {
await store.fetchData();
};
</script>
首先通过useMyStore函数获取了myStore的实例,并将其存储在store变量中。然后,我们定义了incrementCount和fetchData两个函数,分别用于调用store中的increment和fetchData actions。当点击按钮时,这些函数会被触发,从而执行相应的actions并更新状态。