当前位置:   article > 正文

elementUI中loading组件的完美使用_import { loading } from 'element-ui';

import { loading } from 'element-ui';

有时候,网页数据请求太慢,在未得到数据的那一会会,时常会让心急的人怀疑是不是代码哪崩了,所以我需要一个东西来缓冲一下我等待的焦虑,在页面加载时添加一个加载动画

首先安装element-ui框架

npm i elemnt-ui -S

在main.js中引入

  1. import ElementUI from 'element-ui'
  2. import 'element-ui/lib/theme-chalk/index.css'

新建loading.js , 封装loading组件

  1. import { Loading } from 'element-ui';
  2. let loadingCount = 0;
  3. let loading;
  4. const startLoading = () => {
  5. loading = Loading.service({
  6. lock: true,
  7. text: '拼命加载中...',//可以自定义文字
  8. spinner:'el-icon-loading',//自定义加载图标类名
  9. background: 'rgba(0, 0, 0, 0.7)'//遮罩层背景色
  10. });
  11. };
  12. const endLoading = () => {
  13. loading.close();
  14. };
  15. export const showLoading = () => {
  16. if (loadingCount === 0) {
  17. startLoading();
  18. }
  19. loadingCount += 1;
  20. };
  21. export const hideLoading = () => {
  22. if (loadingCount <= 0) {
  23. return;
  24. }
  25. loadingCount -= 1;
  26. if (loadingCount === 0) {
  27. endLoading();
  28. }
  29. };

封装完,就可以在你想使用的地方调用它啦,比如我是用在axios封装里了,每一个发送请求的时候调用他,请求结束获取到数据的时候,关闭他,就很完美啦

  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import {MessageBox} from 'element-ui'
  4. import { showLoading, hideLoading } from './loading';
  5. import router from "../router.js";
  6. axios.defaults.withCredentials = true; //让ajax携带cookie
  7. axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  8. export default function ajax(url, data = {}, type = 'GET') {
  9. showLoading()//显示加载中
  10. return new Promise(function(resolve, reject) {
  11. // 执行异步ajax请求
  12. let promise
  13. if (type === 'GET') {
  14. ...数据处理
  15. // 发送get请求
  16. promise = axios.get(url, data)
  17. } else {
  18. // 发送post请求
  19. promise = axios.post(url, qs.stringify(data))
  20. }
  21. promise.then(function(response) {
  22. hideLoading()//关闭加载
  23. // 成功了调用resolve()
  24. resolve(response.data)
  25. if (response.data.status != 'success') {c
  26. MessageBox.alert(response.data.msg, '错误提示', {
  27. confirmButtonText: '确定',
  28. type: 'error'
  29. });
  30. }
  31. }).catch(function(error) {
  32. hideLoading()//关闭加载
  33. //失败了调用reject()
  34. reject(error)
  35. })
  36. })
  37. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/218963
推荐阅读
相关标签
  

闽ICP备14008679号