1.在components文件夹下创建一个loading组件
2.index.js
import LoadingComponent from "./Loading.vue";
export default {
install: function (Vue) {
Vue.component("loading", LoadingComponent)
}
}
// install 第一个参数是vue的构造器, 第二个参数是可选的选项对象
3.Loading.js
// 这个组件可以写一些自己的动画
<template>
<div><img src="/loading动态图" ></div>
</template>
4.main.js
import Loading from "./components/loading/index"
Vue.use(Loading);
// 这样就可以在vue页面中使用了
5. loading在页面中应用 App.vue
<template>
<div id="app">
<router-view />
<loading v-if="loadingProps.spinning" />
</div>
</template>
<script>
import Vue from "vue";
export default {
name: "Home",
data() {
return {
loadingProps: {
spinning: false,
},
};
},
beforeCreate() {
// 将当前页面组件给到$app
Vue.prototype.$app = this;
}
};
</script>
6.main.js
Vue.prototype.$setLoading = function (props) {
if (typeof props === 'boolean') props = { spinning: props }
if (Object.prototype.toString.call(props) !== '[object Object]') props = {}
console.log(this.$app);
console.log(props);
// this => Vue.Prototype 谁调用this指向谁
this.$app.loadingProps = {
...props
}
}
7.请求时设为true,响应时设为false
import axios from 'axios'
import Vue from 'vue'
import { message } from 'ant-design-vue'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000
})
service.interceptors.request.use(
Vue.prototype.$setLoading(true), // 设为true
// console.log(this.$store.state),
config => {
// if (store.getters.token) {
// config.headers.token = getToken();
// }
return config;
},
error => {
return Promise.reject(error);
}
);
service.interceptors.response.use(
response => {
const res = response.data;
// if (res.code !== 20000) {
// // Message({
// // message: res.message || 'Error',
// // type: 'error',
// // duration: 5 * 1000
// // });
// // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// // MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
// // confirmButtonText: 'Re-Login',
// // cancelButtonText: 'Cancel',
// // type: 'warning'
// // }).then(() => {
// // store.dispatch('user/resetToken').then(() => {
// // location.reload();
// // });
// // });
// // }
// return Promise.reject(new Error(res.message || 'Error'));
// }
Vue.prototype.$setLoading(false); // 响应回来之后设为false
return res;
},
error => {
setTimeout(() => {
Vue.prototype.$setLoading(false); // 请求失败2秒之后设为false
message.error('请求失败', 1);
}, 2000);
return Promise.reject(error);
}
);
export default service;
------------------------------------
~喜欢 的小伙伴点个赞呗,谢谢♥~
--------------------------------------------------------
相关推荐:橘子猫哥的 《普歌-vue实现图片懒加载方式》
---------------------------------------------------
作者:橘子猫哥
出处/源自:[橘子猫哥《普歌-vue中自定义loading组件(不使用UI框架)》]
本文版权归作者和CSDN共有,欢迎转载,且在文章页面明显位置给出原文链接,未经作者同意必须保留此段声明,否则保留追究法律责任的权利。