图片
/**
* Loading 状态管理类
*/
export class Loading {
constructor(timer=300) {
this.value = false
this.timer = timer
}
/**
* 执行异步操作并自动管理 loading 状态
* @param {Promise|Function|any} target - Promise、函数或其他值
* @returns {Promise} - 返回请求结果
*/
async run(target) {
try {
this.value = true
// 先执行函数或获取值
const result = typeof target === 'function' ? target() : target
// 确保结果是 Promise
const promise = result && typeof result.then === 'function'
? result
: new Promise(resolve => {
setTimeout(() => resolve(result), this.timer) // 非异步操作添加延迟
})
return await promise
} finally {
this.value = false
}
}
}
<template>
<div id="app">
{{ loading1.value }}
<a-button type="primary" :loading="loading1.value" @click="handleClick1">
按钮1
</a-button>
</div>
</template>
<script>
import { Loading } from './utils/loading'
export default {
name: 'App',
data() {
return {
loading1: new Loading(),
}
},
methods: {
mockRequest(data) {
return new Promise(resolve => {
setTimeout(() => {
resolve({data:{data}})
}, 400)
})
},
async handleClick1() {
// 1. 直接传入 Promise
// const result1 = await this.loading1.run(this.mockRequest({id:1,name:123}))
// // 2. 传入返回 Promise 的函数
// const result2 = await this.loading1.run(() => this.mockRequest({id:2}))
// // 3. 传入普通函数
// const result3 = await this.loading1.run(() => ({data: {test: 123}}))
// 4. 传入普通值
const result4 = await this.loading1.run({data: {test: 456}})
},
}
}
</script>
<style>
</style>