使用场景
在Pinia中,action用于处理异步操作和复杂的同步操作。它们是store中定义的方法,可以调用其他action或mutation,也可以处理业务逻辑。
基本使用
使用setup()
方法时,可以直接在其中定义action。这些action可以访问响应式状态,并且可以返回Promise。
// 定义store
const useStore = defineStore('main', {
const count = ref(0)
// 定义action
async function increment() {
count.value++
}
return { count, increment }
})
访问其他Store的Action
Pinia允许从一个store访问另一个store的action。这可以通过导入需要的store并直接调用其action来实现。
// 导入另一个store
import useOtherStore from './otherStore'
const useStore = defineStore('main', {
actions: {
async incrementAndLog() {
// 调用当前store的action
this.increment()
// 调用其他store的action
await useOtherStore().logAction()
}
}
})
订阅Action
Pinia提供了订阅功能,允许你在action被调用前后运行一些代码。这对于调试或者插件开发非常有用。
const store = useStore()
store.$onAction({
before: (actionContext) => {
console.log(`before action: ${actionContext.name}`)
},
after: (actionContext) => {
console.log(`after action: ${actionContext.name}`)
},
error: (actionContext) => {
console.log(`error in action: ${actionContext.name}`)
}
})
使用选项式API的Action
选项式API允许你在一个对象中定义state、getters和actions。这种方式更加接近Vue 2的风格。
const useStore = defineStore('main', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
Pinia的action是状态管理的核心部分,它们提供了处理异步和复杂同步操作的能力。合理地使用action可以让你的应用更加模块化和可维护。