vue3+vite全局loading
j-loading.vue组件
<template><transition enter-active-class="animate__animated animate__fadeIn"leave-active-class="animate__animated animate__fadeOut"><div class="root-box" v-if="show"><div class="wrap"><img src="../../assets/img/loading.gif"/></div></div></transition>
</template><script setup>
import {ref} from "vue"
const show = ref(false)const showLoading = () => {show.value = true
}
const hideLoading = (callback) => {show.value = falsecallback && setTimeout(() => callback(), 500)
}defineExpose({show,showLoading,hideLoading
})
//指令使用
// v-jwq-loading="jLoading"//函数使用
// import {getCurrentInstance} from 'vue'
// // 获取当前实例
// const {proxy} = getCurrentInstance()
// 全局显示自定义loading
// const showJwqLoading = () => {
// proxy.$showLoading()
// setTimeout(() => {
// proxy.$hideLoading()
// }, 2000)
// }
</script><style scoped lang="scss">
.animate__animated.animate__fadeIn {--animate-duration: 0.5s;
}.animate__animated.animate__fadeOut {--animate-duration: 0.5s;
}.root-box {position: absolute;left: 0;top: 0;bottom: 0;right: 0;margin: 0;background-color: rgba(255, 255, 255, 0.9);z-index: 2000;display: flex;justify-content: center;align-items: center;.wrap {width: 300px;height: 300px;display: flex;justify-content: center;align-items: center;overflow: hidden;img {width: 100%;//transform: scale(2.5);}}
}
</style>
jLoadding.js
import {createVNode, render, cloneVNode} from "vue"
import jLoading from "./j-loading.vue"export default {install(app) {const VNode = createVNode(jLoading)render(VNode, document.body)app.config.globalProperties.$showLoading = VNode.component.exposed.showLoadingapp.config.globalProperties.$hideLoading = VNode.component.exposed.hideLoadingconst weakMap = new WeakMap()app.directive("jwq-loading", {mounted(el) {if (weakMap.get(el)) returnweakMap.set(el, window.getComputedStyle(el).position)},updated(el, binding) {const oldPosition = weakMap.get(el);if (oldPosition !== 'absolute' && oldPosition !== 'relative') {el.style.position = 'relative'}const newVNode = cloneVNode(VNode)render(newVNode, el)if (binding.value) {newVNode.component.exposed.showLoading()} else {newVNode.component.exposed.hideLoading(() => {el.style.position = oldPosition})}}})}
}
main.js
import jLoading from "./components/j-loading/jLoading.js"
app.use(jLoading)
全局设置请求
import jLoading from "@/components/j-loading/j-loading.vue"
import {createVNode, render} from "vue";
const VNode = createVNode(jLoading)
render(VNode, document.body)
const showLoading=()=>{VNode.component.exposed.showLoading()
}
const hideLoading=()=>{VNode.component.exposed.hideLoading()
}
export function get(url, params = {}) {return new Promise((resolve, reject) => {showLoading()axios.get(url, {params: params}).then(response => {hideLoading()resolve(response);}).catch(err => {reject(err)})})
}