首页 > 技术文章 > Vue 使用 axios 或者 vue-router 配置页面加载动画

blackbentel 2018-05-31 16:53 原文

先提一笔,这篇文章是关于 Vue 页面加载动画的实现

以下介绍两种方法

  1. 使用 axios 配置全局中当发生 ajax 请求时,显示一个加载动画,当 ajax 请求结束后,隐藏加载动画
  2. 使用 Vue-router 实现当页面跳转时有一个加载动画

第一种方式, 配置 axios 实现加载动画

在 axios 的拦截器中实现

1. 在 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>

 

2. 在Vuex 中托管  loading 

 1 export default new Vuex.Store({
 2   state: {
 3     loading: true
 4   },
 5   mutations: {
 6     loadStatus (state, flag) {
 7       state.loading = flag
 8     }
 9   }
10 }

 

3. Axios 拦截器中配置请求时显示加载动画,请求完成隐藏加载动画

项目中一般需要将axios封装,我们就在该文件中的拦截器中添加代码

首先需要在文件中引入 VueX 实例,也就是代码中的 store, 通过这个 store 我们才能访问到 Vuex中的数据

  •  在请求拦截中触发VueX中的  loadStatus 方法,使加载动画显示
  •  在响应拦截中同样触发  loadStatus 方法,试加载动画隐藏
 1 import axios from 'axios'
 2 import store from '@/store'
 3 // 请求拦截
 4 axios.interceptors.request.use(res => {
 5   store.commit('loadStatus', true)
 6   return Promise.resolve(res)
 7 }, error => {
 8   return Promise.reject(error)
 9 })
10 
11 // 响应拦截
12 axios.interceptors.response.use(res => {
13   if (res.status === 200) {
14     store.commit('loadStatus', false)
15     return Promise.resolve(res)
16   } else {
17     MessageBox('提示', '服务器出问题了,请重新进入试试')
18   }
19 }, error => {
20   MessageBox('提示', '服务器出问题了,请重新进入试试')
21   return Promise.reject(error)
22 })

 

 

第二种方式, 配置 axios 实现加载动画

方式一的第一步和第二步照搬下来

第三步:配置 vue-router,添加 路由守卫 

  1. 引入 store
  2. 在  router.beforeEach  方法中触发 loadStatus, 显示加载动画, next()  方法一定要有,否则加载不出页面的
  3. 在  router.afterEach  方法中触发 loadStatus, 隐藏加载动画
 1 import Vue from 'vue'
 2 import Router from 'vue-router'
 3 import routes from './router.api'
 4 import store from '@/store'
 5 Vue.use(Router)
 6 
 7 const router = new Router({
 8   routes
 9 })
10 router.beforeEach((to, from, next) => {
11   store.commit('loadStatus', true)16   next()
17 })
18 
19 router.afterEach(function (to) {
20   store.commit('loadStatus', false)
21 })
22 export default router

 

以上就是在 Vue 项目中使用axios 或者 vue-router 配置页面加载动画

 

推荐阅读