以下介绍两种方法
1.使用 axios 配置全局中当发生 ajax 请求时,显示一个加载动画,当 ajax 请求结束后,隐藏加载动画
2.使用 Vue-router 实现当页面跳转时有一个加载动画
方式一 配置 axios 实现加载动画
- 第一步:在 App.vue 文件中添加你的加载动画组件 或者 HTML,因为加载动画是全局的,所以应该放在 App.vue ,下面示例中我用的是 mint-ui 里面的spinner,然后通过Vuex this.$store.state.loading 来控制,该加载动画的显示隐藏
<template>
<div id="app">
<router-view />
<div class="appLoading" ref="appLoading" v-show="this.$store.state.loading">
<mt-spinner type="triple-bounce" color="rgb(38, 162, 255)"></mt-spinner>
</div>
</div>
</template>
- 第二步:在Vuex 中托管 loading
export default new Vuex.Store({
state: {
loading: true
},
mutations: {
loadStatus (state, flag) {
state.loading = flag
}
}
}
- 第三步:Axios 拦截器中配置请求时显示加载动画,请求完成隐藏加载动画
项目中一般需要将axios封装,我们就在该文件中的拦截器中添加代码,首先需要在文件中引入 VueX 实例,也就是代码中的 store, 通过这个 store 我们才能访问到 Vuex中的数据,在请求拦截中触发VueX中的 loadStatus 方法,使加载动画显示,在响应拦截中同样触发 loadStatus 方法,试加载动画隐藏。
import axios from 'axios'
import store from '@/store'
// 请求拦截
axios.interceptors.request.use(res => {
store.commit('loadStatus', true)
return Promise.resolve(res)
}, error => {
return Promise.reject(error)
})
// 响应拦截
axios.interceptors.response.use(res => {
if (res.status === 200) {
store.commit('loadStatus', false)
return Promise.resolve(res)
} else {
MessageBox('提示', '服务器出问题了,请重新进入试试')
}
}, error => {
MessageBox('提示', '服务器出问题了,请重新进入试试')
return Promise.reject(error)
})
方式二 配置 axios 实现加载动画
-
方式一的第一步和第二步照搬下来
-
第三步:配置 vue-router,添加 路由守卫
引入 store
在 router.beforeEach 方法中触发 loadStatus, 显示加载动画, next() 方法一定要有,否则加载不出页面的
在 router.afterEach 方法中触发 loadStatus, 隐藏加载动画
import Vue from 'vue'
import Router from 'vue-router'
import routes from './router.api'
import store from '@/store'
Vue.use(Router)
const router = new Router({
routes
})
router.beforeEach((to, from, next) => {
store.commit('loadStatus', true)16 next()
})
router.afterEach(function (to) {
store.commit('loadStatus', false)
})
export default router