赞
踩
有时候,网页数据请求太慢,在未得到数据的那一会会,时常会让心急的人怀疑是不是代码哪崩了,所以我需要一个东西来缓冲一下我等待的焦虑,在页面加载时添加一个加载动画
首先安装element-ui框架
npm i elemnt-ui -S
在main.js中引入
- import ElementUI from 'element-ui'
- import 'element-ui/lib/theme-chalk/index.css'
新建loading.js , 封装loading组件
- import { Loading } from 'element-ui';
-
- let loadingCount = 0;
- let loading;
-
- const startLoading = () => {
- loading = Loading.service({
- lock: true,
- text: '拼命加载中...',//可以自定义文字
- spinner:'el-icon-loading',//自定义加载图标类名
- background: 'rgba(0, 0, 0, 0.7)'//遮罩层背景色
- });
- };
-
- const endLoading = () => {
- loading.close();
- };
-
- export const showLoading = () => {
- if (loadingCount === 0) {
- startLoading();
- }
- loadingCount += 1;
- };
-
- export const hideLoading = () => {
- if (loadingCount <= 0) {
- return;
- }
- loadingCount -= 1;
- if (loadingCount === 0) {
- endLoading();
- }
- };

封装完,就可以在你想使用的地方调用它啦,比如我是用在axios封装里了,每一个发送请求的时候调用他,请求结束获取到数据的时候,关闭他,就很完美啦
- import axios from 'axios'
- import qs from 'qs'
- import {MessageBox} from 'element-ui'
- import { showLoading, hideLoading } from './loading';
- import router from "../router.js";
- axios.defaults.withCredentials = true; //让ajax携带cookie
- axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
- export default function ajax(url, data = {}, type = 'GET') {
- showLoading()//显示加载中
- return new Promise(function(resolve, reject) {
- // 执行异步ajax请求
- let promise
- if (type === 'GET') {
- ...数据处理
- // 发送get请求
- promise = axios.get(url, data)
- } else {
- // 发送post请求
- promise = axios.post(url, qs.stringify(data))
- }
- promise.then(function(response) {
- hideLoading()//关闭加载
- // 成功了调用resolve()
- resolve(response.data)
- if (response.data.status != 'success') {c
- MessageBox.alert(response.data.msg, '错误提示', {
- confirmButtonText: '确定',
- type: 'error'
- });
- }
- }).catch(function(error) {
- hideLoading()//关闭加载
- //失败了调用reject()
- reject(error)
- })
- })
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。