vue3自定义loading加载动画指令
//vLoading.ts
import { ref, watch } from 'vue';
let divEle:any = null
// 创建一个 ref 用于管理加载状态
export const vloadingShow = ref(false);
export const vLoading = {
mounted(el: any, binding: any) {
//
const loadingDiv: any = document.createElement('div');
loadingDiv.classList.add('Svloading');
loadingDiv.style.position = 'fixed';
loadingDiv.style.top = '0';
loadingDiv.style.left = '0';
loadingDiv.style.width = '100%';
loadingDiv.style.height = '100%';
loadingDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.2)';
loadingDiv.style.display = 'flex';
loadingDiv.style.justifyContent = 'center';
loadingDiv.style.alignItems = 'center';
loadingDiv.style.zIndex = 9999;
loadingDiv.style.userSelect = 'none';
loadingDiv.style.webkitUserSelect = 'none';
loadingDiv.style.msUserSelect = 'none';
// 关闭的按钮
const closeButton:any = document.createElement('div');
closeButton.textContent = '关闭';
closeButton.style.position = 'absolute';
closeButton.style.top = '10px';
closeButton.style.right = '10px';
closeButton.style.backgroundColor = 'transparent';
closeButton.style.color = 'white';
closeButton.style.border = 'none';
closeButton.style.fontSize = '20px';
closeButton.style.cursor = 'pointer';
closeButton.addEventListener('click', () => {
vloadingShow.value = false;
});
const img = document.createElement('img');
img.src = '/svLogo.gif';
img.alt = '加载中。。。';
img.style.width = '100px';
loadingDiv.appendChild(img);
loadingDiv.appendChild(closeButton);
el.loadingDiv = loadingDiv;
divEle = loadingDiv
if (vloadingShow.value) {
document.body.appendChild(loadingDiv);
}
},
unmounted(el: any) {
// 组件销毁时,移除 Svloading 元素
const loadingDiv = el.loadingDiv;
if (loadingDiv) {
const parent = loadingDiv.parentNode;
if (parent) {
parent.removeChild(loadingDiv);
}
}
},
};
watch(() => vloadingShow.value, (newVal) => {
if (newVal && divEle) {
document.body.appendChild(divEle);
} else {
// 如果需要隐藏加载,移除所有加载元素
const loadingElements = document.querySelectorAll('.Svloading');
loadingElements.forEach((element) => {
const parent = element.parentNode;
if (parent) {
parent.removeChild(element);
}
});
}
});
//main.ts
import { vLoading } from '@/utils/directive/vLoading';
const app = createApp(App);
// 注册指令
app.directive('Svloading', vLoading);
app.mount('#app')
使用