Vue 全局 loading 的实现思路一般是在 Vue 实例中添加一个 loading 组件,通过控制该组件的显示和隐藏来实现全局 loading 的效果。
具体思路如下:
- 创建一个全局的 Vue 组件 Loading,该组件用于显示 loading 状态。
<template>
<div class="loader" v-show="visible">
<div class="inner one"></div>
<div class="inner two"></div>
<div class="inner three"></div>
<!-- <p class="loader_text">加载中... ...</p> -->
</div>
</template>
<script>
export default {
data() {
return {
// visible: false,
};
},
props: {
visible: Boolean,
},
methods: {
// show() {
// console.log("显示loading");
// this.visible = true;
// },
// hide() {
// console.log("隐藏loading");
// this.visible = false;
// },
},
mounted() {
this.$nextTick(() => {
this.visible = false;
});
},
};
</script>
<style scoped>
.loader {
position: fixed;
top: calc(50% - 150px);
left: calc(50% - 82px);
width: 164px;
height: 164px;
border-radius: 50%;
perspective: 800px;
}
.inner {
position: absolute;
box-sizing: border-box;
width: 100%;
height: 100%;
border-radius: 50%;
}
.inner.one {
left: 0%;
top: 0%;
animation: rotate-one 1.4s linear infinite;
border-bottom: 6px solid #0060ca;
}
.inner.two {
right: 0%;
top: 0%;
animation: rotate-two 1.4s linear infinite;
border-right: 6px solid #ffbf00;
}
.inner.three {
right: 0%;
bottom: 0%;
animation: rotate-three 1.4s linear infinite;
border-top: 6px solid #29dcf1;
}
@keyframes rotate-one {
0% {
transform: rotateX(35deg) rotateY(-45deg) rotateZ(0deg);
}
100% {
transform: rotateX(35deg) rotateY(-45deg) rotateZ(360deg);
}
}
@keyframes rotate-two {
0% {
transform: rotateX(50deg) rotateY(10deg) rotateZ(0deg);
}
100% {
transform: rotateX(50deg) rotateY(10deg) rotateZ(360deg);
}
}
@keyframes rotate-three {
0% {
transform: rotateX(35deg) rotateY(55deg) rotateZ(0deg);
}
100% {
transform: rotateX(35deg) rotateY(55deg) rotateZ(360deg);
}
}
.loader_text {
font-size: 25px;
color: #0060ca;
text-align: center;
padding-top: 190px;
}
</style>
- 创建一个js文件 loading.js
import Vue from "vue";
import componentLoading from "../../components/overallLoading";
const comLoading = Vue.extend(componentLoading);
const instance = new comLoading({
el: document.createElement("div"),
});
instance.visible = false;
const loading = {
show() {
instance.visible = true;
document.body.appendChild(instance.$el);
},
hide() {
instance.visible = false;
},
};
export default {
install() {
if (!Vue.$loading) {
Vue.$loading = loading;
}
Vue.mixin({
created() {
this.$loading = Vue.$loading;
},
});
},
};
- 在 main.js 中注册 Loading 组件,并挂载到 Vue 实例上。
// 全局引入loading
import loadong from "./assets/js/loading";
Vue.use(loadong);
new Vue({
el: '#app',
render: h => h(App)
});
在需要显示 loading 的地方,调用全局方法 $loading.show(),该方法通过修改 loading 组件的状态来显示 loading。
在需要隐藏 loading 的地方,调用全局方法 $loading.hide(),该方法通过修改 loading 组件的状态来隐藏 loading。
全局使用:
this.$loading.show();
this.$loading.hide();