使用antdv 后发现只有button支持loaidng属性,而其他元素不能使用loading来显示是否加载中,需要套一层 a-spin 才能支持,非常不方便。
所以写了个自定义的指令来进行处理
新建loading.vue文件用来页面显示
<template><div class="loading-container"><LoadingOutlined /><p>{{ state.loading.text }}</p></div>
</template>
<script lang="ts" setup>
import { LoadingOutlined } from '@ant-design/icons-vue';
import { reactive } from 'vue';
const FONT_SIZE = {samll: {icon: '16px',p: '12px'},default: {icon: '20px',p: '16px'},large: {icon: '24px',p: '20px'}
}
const state = reactive({loading: {text: '正在加载中',fontSize: {icon: '20px',p: '16px'}} as { text?: string; fontSize?: { icon: string; p: string } }
})function updateInfo(params: { text: string; size: 'samll' | 'default' | 'large' }) {state.loading = {text: params.text,fontSize: FONT_SIZE[params.size]}
}defineExpose({ updateInfo })</script>
<style lang="scss" scoped>
.loading-container {position: absolute;left: 0;top: 0;height: 100%;width: 100%;overflow: hidden;background: rgba($color: #ffffff, $alpha: 0.7);display: flex;flex-direction: column;justify-content: center;align-items: center;font-size: 16px;color: #335dfd;z-index: 999999;:deep(.anticon-loading) {font-size: 20px;}p {margin-top: 10px;font-size: 16px;}
}
</style>
在新建个loading.ts 用来注册v-loading 相关操作
import { createApp, Directive } from 'vue';
import Loading from './index.vue';
/*** @description 判断是否为空对象* **/
export const isEmptyObj = (obj: object): boolean => {return JSON.stringify(obj) === "{}";
};/** v-eLoading:[loadingConfig]="state.l||state.a */
const loading: Directive = {mounted(el, binding) {const app = createApp(Loading);const instance = app.mount(document.createElement('div')) as any;el.instance = instance;el.style.position = 'relative';const arg:any = binding.argif (!isEmptyObj(arg as any)){const params = {text:arg?.text||'正在加载中',size:'default'}instance.updateInfo(params)}if (binding.value) {appendEl(el);}},updated(el, binding) {console.log(binding.value !== binding.oldValue)if (binding.value !== binding.oldValue) {binding.value ? appendEl(el) : removeEl(el);}},
};const appendEl = (el: { appendChild: (arg0: any) => void; instance: { $el: any; }; }) => {el.appendChild(el.instance.$el);
};const removeEl = (el: { removeChild: (arg0: any) => void; instance: { $el: any; }; }) => {el.removeChild(el.instance.$el);
};export default loading;
最后在main.ts 进行注册
import loadingDirective from 'packages\Loading\index.ts'
createApp(App).directive('loading', loadingDirective).mount('#app')
在页面中就可以直接进行v-loading 进行使用了
<div v-loading="true"></div>