Pinia核心概念:Actions详解与应用指南
2025-07-06 02:26:32作者:凌朦慧Richard
什么是Actions
在Pinia状态管理库中,Actions相当于组件中的methods,用于封装业务逻辑。通过defineStore()
中的actions
属性定义,它们可以同步或异步地修改状态。
基本用法
定义Actions
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
},
randomizeCounter() {
this.count = Math.round(100 * Math.random())
},
}
})
关键点:
- 使用常规函数而非箭头函数,以保持正确的
this
绑定 - 通过
this
可以访问整个store实例 - 支持完整的TypeScript类型推断和代码补全
异步Actions示例
export const useUsers = defineStore('users', {
state: () => ({
userData: null
}),
actions: {
async registerUser(login, password) {
try {
this.userData = await api.post({ login, password })
showTooltip(`Welcome back ${this.userData.name}!`)
} catch (error) {
showTooltip(error)
return error
}
}
}
})
异步操作特点:
- 支持
async/await
语法 - 可以自由组合多个异步操作
- 错误处理与常规Promise一致
高级用法
跨Store调用
Actions可以方便地调用其他store中的方法:
import { useAuthStore } from './auth-store'
export const useSettingsStore = defineStore('settings', {
actions: {
async fetchUserPreferences() {
const auth = useAuthStore()
if (auth.isAuthenticated) {
this.preferences = await fetchPreferences()
} else {
throw new Error('User must be authenticated')
}
}
}
})
与Options API配合
使用setup()方式
<script>
import { useCounterStore } from '../stores/counter'
export default defineComponent({
setup() {
const counterStore = useCounterStore()
return { counterStore }
},
methods: {
incrementAndPrint() {
this.counterStore.increment()
console.log('New Count:', this.counterStore.count)
}
}
})
</script>
使用mapActions辅助函数
import { mapActions } from 'pinia'
import { useCounterStore } from '../stores/counter'
export default {
methods: {
...mapActions(useCounterStore, ['increment']),
...mapActions(useCounterStore, { myOwnName: 'increment' })
}
}
动作订阅机制
Pinia提供了强大的动作订阅API,可以监听action的执行过程:
const unsubscribe = store.$onAction(({
name, // 动作名称
store, // store实例
args, // 调用参数数组
after, // 动作成功后的回调
onError // 动作失败后的回调
}) => {
const startTime = Date.now()
console.log(`开始执行 "${name}",参数: [${args.join(', ')}]`)
after((result) => {
console.log(`"${name}" 执行完成,耗时 ${Date.now() - startTime}ms`)
})
onError((error) => {
console.warn(`"${name}" 执行失败,耗时 ${Date.now() - startTime}ms`)
})
})
// 取消订阅
unsubscribe()
订阅特性:
- 默认随组件卸载自动取消
- 可通过第二个参数
true
保持持久化订阅 - 适用于日志记录、性能监控等场景
最佳实践
- 业务逻辑集中化:将与状态相关的业务逻辑封装在actions中,保持组件简洁
- 错误处理规范化:统一处理异步操作错误,提供一致的用户体验
- 组合优于继承:通过组合多个store的actions构建复杂业务流
- 合理使用订阅:用于调试和监控,避免过度使用影响性能
Actions作为Pinia三大核心概念之一,与State和Getters共同构成了完整的状态管理体系。合理使用Actions可以使您的应用逻辑更清晰、更易于维护。