43 lines
1.1 KiB
TypeScript
43 lines
1.1 KiB
TypeScript
import { ref } from 'vue'
|
|
|
|
import { isFeedbackDismissed, showConfirm, showError, showSuccess } from '@/lib/feedback'
|
|
|
|
export interface RunActionOptions {
|
|
id: number | string
|
|
action: () => Promise<unknown>
|
|
successMessage: string
|
|
confirmText: string
|
|
onAfterAction?: () => Promise<unknown> | void
|
|
}
|
|
|
|
export function useAdminAction() {
|
|
const actionLoadingId = ref<number | string | null>(null)
|
|
|
|
async function runAction(options: RunActionOptions) {
|
|
try {
|
|
await showConfirm(options.confirmText, '确认操作', {
|
|
type: 'warning',
|
|
confirmButtonText: '继续执行',
|
|
cancelButtonText: '取消',
|
|
})
|
|
} catch (error) {
|
|
if (isFeedbackDismissed(error)) return
|
|
throw error
|
|
}
|
|
|
|
actionLoadingId.value = options.id
|
|
|
|
try {
|
|
await options.action()
|
|
showSuccess(options.successMessage)
|
|
if (options.onAfterAction) await options.onAfterAction()
|
|
} catch (error) {
|
|
showError(error instanceof Error ? error.message : '操作失败')
|
|
} finally {
|
|
actionLoadingId.value = null
|
|
}
|
|
}
|
|
|
|
return { actionLoadingId, runAction }
|
|
}
|