第一步:在components下自定义一个文件夹loading.js,利用V-directive封装
import Vue from 'vue'
import imgUrl from '../../assets/img/loading.gif'//自定义加载中的gif动图
const insertDom = (parent,el)=>{
parent.appendChild(el.mask)
}
const removeChildDom = (parent,el) =>{
parent.removeChild(el.mask)
}
const toggleLoading = (el,binding) =>{
if(binding.value){
Vue.nextTick(() =>{
insertDom(el,el,binding)
})
}else{
removeChildDom(el,el,binding)
}
}
export default{
bind(el,binding,vnode){
let mask = document.createElement('div')
mask.classList.add('loading-container')//给创建的div加入loading-container样式
mask.innerHTML = `<img src="${imgUrl}"/>`//新的div下加入自定义的gif动图
el.style.position = 'relative'
el.style.height = '100%'
el.mask = mask
binding.value && toggleLoading(el,binding)
},
update(el,binding){
if(binding.oldValue !== binding.value){
toggleLoading(el,binding)
}
}
}
第二步:在main.js中引入组件
//引入自定义封装的组件
import Loading from './components/loading.js'
Vue.directive('maskLoading',Loading)
第三步:在对应div上绑定v-maskLoading
<template>
//maskLoading,请求接口前设置为true,请求结束后设置为false
<div v-maskLoading="maskLoading">
</div>
</template>
<script>
export default{
data(){
return {
maskLoading:false
}
}
}
</script>
<style scoped>
</style>
样式:
.loading-container{
position:absolute;
z-index:50;
left:0;
top: 0;
bottom: 0;
right: 0;
background-color:#fff;
display:flex;
justify-content:center;
align-items:center;
}
又是愉快搬砖撸代码的一天!!!