vue3与elementui封装一个便捷Loading
作者:Daiyaosei
这篇文章主要介绍了vue3与elementui封装一个便捷Loading,,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
前言
因为后台管理,总要写很多loading状态的变量,然后控制开启和关闭。。我个人很讨厌写这种重复的代码。。所以为了少写点这种变量,所以突发奇想封装一个,目前感觉还是挺好用的,没出啥bug。。。在表格中也能运用自如。。喜欢的话,可以复制到你自己的项目拿去用,记得点个赞噢
实际使用
代码实现
import { reactive } from 'vue' import { ElMessageBox, ElMessage } from 'element-plus' import { isArray } from 'lodash-es' // 过滤表单 import { filterForm } from '@/utils' interface SubmitType { loading?: string params?: any successText?: string errorText?: string message?: string title?: string } interface SubmitParamsType { loadingText?: string params?: any api: Function success?: string error?: string submitMessage?: string } interface UpdateType { loading?: string params?: any api?: Function successText?: string errorText?: string } interface CrudLoadingType { [_submitLoading: string]: boolean } interface UpdateLoadingType { [_updateLoading: string]: boolean } const submitDataHook = (context: SubmitType) => { const { loading = '_submitLoading', successText = '操作成功', errorText = '操作失败', message = '是否进行提交', title = '温馨提示' } = context const submitLoading = reactive({}) as CrudLoadingType const submitHook = ({ params, api, loadingText = loading, success = successText, error = errorText, submitMessage = message }: SubmitParamsType) => { return new Promise((resolve, reject) => { submitLoading[loadingText as string] = true ElMessageBox.confirm(submitMessage, title) .then(() => { return api(isArray(params) ? params : filterForm(params)) .then((data) => { ElMessage.success(success) resolve(data) return data }) .catch((res) => { reject(res) if (res.code === '1' && !res.msg) { ElMessage.error(error) } }) }) .catch(() => { reject() ElMessage.warning('取消操作') }) .finally(() => { submitLoading[loadingText as string] = false }) }) } return { submitHook, submitLoading } } const updateData = (context: UpdateType) => { const { loading = '_updateLoading', successText = '操作成功', errorText = '操作失败' } = context const updateLoading = reactive({ [loading]: false }) as UpdateLoadingType const updateHook = ({ params, api, success = successText, error = errorText, loadingText = loading }: SubmitParamsType) => { updateLoading[loadingText] = true return api(isArray(params) ? params : filterForm(params)) .then((data) => { ElMessage.success(success) return data }) .catch((e) => { ElMessage.error(error) throw e }) .finally(() => { updateLoading[loadingText] = false }) } return { updateHook, updateLoading } } export { submitDataHook, updateData }
到此这篇关于vue3与elementui封装一个便捷Loading的文章就介绍到这了,更多相关vue3封装Loading内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!