vue前端页面数据加载添加loading效果的实现

前端页面数据加载添加loading效果

在前端上传文件或者加载数据的时候会有一段等待时间,如果加上一个loading效果会减轻用户等待的枯燥,这里就来记录学习一下如何实现loading效果。

vue前端页面数据加载添加loading效果的实现_第1张图片

效果大致如下,样式我们是可以自定义的。

具体实现

let thisContent = this;
let loading = thisContent.$loading({
        lock: true,
        text: '上传中,请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
// 中间进行一系列的操作
// 上传成功后关闭loading, 并显示上传成功
loading.close();
thisC.$message('上传文件成功');

这样一个简单的loading效果就实现了。

全局loading配置

请求的时候 需要一个全局loading来拦截 若是页面单独引用的话 就有点繁琐了 所以需要再全局封装一个 此时就要明白 再哪里封装了 先考虑一下 为什么要用

一方面是为了防止重复操作

另一方面是为了一个加载的效果能够更明显 

所以 再请求的时候加 就能联想到axios拦截器的位置处理了 话不多说 开始撸代码 全程copy就行了  

1 再src/componennts/Spinner下面建立一个index.vue


 

 

2 再utils下面tools.js

class Msg {
  static loading() {
    document.querySelector('.loading-page').style.display = 'block';
  }
 
  static hideLoading() {
    document.querySelector('.loading-page').style.display = 'none';
  }
}
 
export {
  Tools,
  Msg
}

3 再utils下面建议一个request.js 封装的axios请求

import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import {Msg} from '@/utils/tools';
import { removeToken } from '@/utils/auth'
 
var allResquest = 0;
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
    withCredentials: true, // 跨域请求时发送 cookies
    paramsSerializer: params => { // 查询字符串中的数组不使用方括号
			return qs.stringify(params, { indices: false })
		},
    timeout: 15000 // request timeout
})
 
// request interceptor
service.interceptors.request.use(
    config => {
      if (store.getters.token) {
            config.headers['Authorization'] = 'Bearer ' + getToken()
            config.headers['filterMode'] = localStorage.getItem('dataType')
        }
      config.headers['project'] = "csr"
      allResquest = allResquest + 1;
      if (config.mask !== true)  {
        Msg.loading()
      }
      return config
    },
    error => {
        return Promise.reject(error)
    }
)
 
// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get information such as headers or status
     * Please return  response => response
     */
    /**
     * 下面的注释为通过在response里,自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题,登出并返回到登录页
     * 如想通过 XMLHttpRequest 来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例,请结合自生需求加以修改,若不需要,则可删除
     */
    response => {
        allResquest = allResquest - 1;
        const res = response.data;
        if (response.status === 200) {
          if (allResquest === 0) {
            Msg.hideLoading();
          }
            // 50008 系统无此账号
            // 50010 账号禁用
            // 50012 账号或密码错误
            // 50013 主账号被禁用,禁止登录
            // 50014 token失效
            // 50015 登录失败,无操作权限,请联系系统管理员!
            // 50016 验证码错误
            // 429   限流 服务器拥挤,请稍后再试
            // -999  未知错误
            // 403  无权限
            if (res.code === 50008 || res.code === 50010 || res.code === 50012 || res.code === 50013 ||
              res.code === 50016 || res.code === 50015 || res.code === 429 || res.code === -999 || res.code === 403 || res.code === 500) {
                Message({
                    message: res.msg || 'error',
                    type: 'error',
                    duration: 5 * 1000,
                    offset: 0
                })
              return Promise.reject(res.msg || 'error')
            } else if (res.code === 50014) {
              if (store.getters.token) {
                removeToken()
              }
              MessageBox.alert( res.msg,'错误提示', {
                confirmButtonText: '确定',
                callback: action => {
                  store.dispatch('logout')
                  router.push(`/login`)
                }
              })
              return false
            }
            return res
        }
    },
    error => {
        allResquest = allResquest - 1;
        Msg.hideLoading();
        Message({
            message: '服务拥挤,请稍后重试!',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)
export default service

4 修改app.vue

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(vue前端页面数据加载添加loading效果的实现)