diff --git a/.gitignore b/.gitignore index a547bf36d8d11a4f89c59c144f24795749086dd1..ea437045e99d2f4081309e7fd535e4e600211ba7 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,5 @@ dist-ssr *.njsproj *.sln *.sw? + +yarn.lock diff --git a/src/components/Loading.vue b/src/components/Loading.vue new file mode 100644 index 0000000000000000000000000000000000000000..ccc22037f5f2959e22464316fbc4c0abfd3d6e68 --- /dev/null +++ b/src/components/Loading.vue @@ -0,0 +1,116 @@ + + + + + diff --git a/src/utils/loading.ts b/src/utils/loading.ts new file mode 100644 index 0000000000000000000000000000000000000000..381cdeb4c3de434aca22198e52cb850022c7464b --- /dev/null +++ b/src/utils/loading.ts @@ -0,0 +1,43 @@ +import {createApp, reactive} from "vue"; +import Loading from "@/components/Loading.vue"; + +const options = reactive({ + showLoading: false +}); + +const divDom = document.createElement('div'); +const $loading = createApp(Loading, { options }).mount(divDom); + +export class AxiosLoading { + private loadingCount: number + private loading: any + + constructor() { + this.loadingCount = 0 + } + + private initLoading() { + if (this.loading) { + options.showLoading = false; + } + document.body.appendChild(divDom); + this.loading = $loading; + options.showLoading = true; + } + + public addLoading() { + if (this.loadingCount === 0) { + this.initLoading() + } + this.loadingCount++ + } + + public closeLoading() { + if (this.loadingCount > 0) { + if (this.loadingCount === 1) { + options.showLoading = false; + } + this.loadingCount-- + } + } +} diff --git a/src/utils/request.ts b/src/utils/request.ts index 7d8330a99796db34e69db75aa43cb45ddd30cf80..f1985798bbaa16fcb1a46f39c8ff48cf50468b6a 100644 --- a/src/utils/request.ts +++ b/src/utils/request.ts @@ -1,5 +1,6 @@ import Axios from 'axios' +import {AxiosLoading} from "@/utils/loading"; const baseURL = import.meta.env.VITE_API_BASEURL @@ -8,9 +9,12 @@ const axios = Axios.create({ timeout: 20000 // 请求超时 20s }) +const loading = new AxiosLoading(); + // 前置拦截器(发起请求之前的拦截) axios.interceptors.request.use( (response) => { + loading.addLoading(); /** * 根据你的项目实际情况来对 config 做处理 * 这里对 config 不做任何处理,直接返回 @@ -25,6 +29,7 @@ axios.interceptors.request.use( // 后置拦截器(获取到响应时的拦截) axios.interceptors.response.use( (response) => { + loading.closeLoading() /** * 根据你的项目实际情况来对 response 和 error 做处理 * 这里对 response 和 error 不做任何处理,直接返回 @@ -32,6 +37,7 @@ axios.interceptors.response.use( return response }, (error) => { + loading.closeLoading() if (error.response && error.response.data) { const code = error.response.status const msg = error.response.data.message @@ -43,4 +49,4 @@ axios.interceptors.response.use( } ) -export default axios \ No newline at end of file +export default axios