Vue3+TS项目给el-button统一封装一个点击后转圈效果的钩子函数按钮防抖
前言
每个按钮都要单独定义一个loading变量,并且在接口请求前修改为true,接口响应后再修改为false,封装后这段重复的逻辑就可以统一管理不用每次都写一遍了。
效果
新建一个公共的src\common.ts
import { ref } from "vue"
export function useBtnLoading() {
const isLoading = ref(false)
const handleClick = async (action: () => Promise<void>) => {
isLoading.value = true
try {
await action()
} finally {
isLoading.value = false
}
}
return {
isLoading,
handleClick,
}
}
页面中使用
<el-button type="primary" :loading="btnLoading" @click="btnClick">提交</el-button>
import { useBtnLoading } from '@/utils/common'
const { isLoading: btnLoading, handleClick } = useBtnLoading();
const btnClick = () => {
handleClick(() => reqFn())
}
const reqFn = () => {
// 模拟调用接口
return new Promise((resolve, reject) => {
setTimeout(() => resolve(123), 2000);
});
}