vue3自定义loading加载动画指令

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')

使用


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值