关于使用ElLoading 自定义loading效果

fullLoadinng.js

import { ElLoading } from 'element-plus'

import { debounce } from 'lodash'

let loading = null

// 当前loading接口请求数量,用于判断避免生成多个loading

let needLoadingRequestCount = 0

// lodaing配置

const lodingOptions = {

    lock: true,

    text: '',

    customClass: 'eda-full-loading',

    // background: 'rgba(0, 0, 0, 0.7)',

}

/**

 * @description: 触发loding显示

 * @return {*}

 */

export function showLoading() {

    if (needLoadingRequestCount === 0 && !loading) {

        loading = ElLoading.service(lodingOptions)

    }

    needLoadingRequestCount ++

}

/**

 * @description: 关闭loading显示

 * @return {*}

 */

export function hideLoading() {

    needLoadingRequestCount --

    // 数值保护,避免出现负数

    needLoadingRequestCount = Math.max(needLoadingRequestCount, 0)

    if (needLoadingRequestCount === 0) {

        toHideLoading()

    }

}

const toHideLoading = debounce(() => {

    loading?.close()

    loading = null

}, 300)

index.css

// 请求全局加载

.eda-full-loading {

    .el-loading-spinner {

        .circular {

            display: none;

        }

        background: url(../images/loading.gif) no-repeat;

        background-size: 200px 200px;

        width: 200px;

        height: 200px;

        position: absolute;

        text-align: center;

        top: calc(50% - 100px);

        left: calc(50% - 100px);

    }

}

request.js

import axios from 'axios'

import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'

import store from '@/store'

import { getToken } from '@/utils/auth'

import errorCode from '@/utils/errorCode'

import { tansParams, blobValidate } from '@/utils/ruoyi'

import cache from '@/plugins/cache'

import { saveAs } from 'file-saver'

import i18n from '@/languages/i18n.js'

const { t } = i18n.global

import { showLoading, hideLoading } from '@/utils/fullLoadinng'

let downloadLoadingInstance;

// 是否显示重新登录

export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例

const service = axios.create({

  // axios中请求配置有baseURL选项,表示请求URL公共部分

  baseURL: import.meta.env.VITE_APP_BASE_API,

  // 为配合后端,超时时间设置为30s

  timeout: 30000,

})

let configCache = null

// request拦截器

service.interceptors.request.use(config => {

  // 是否需要设置 token

  const isToken = (config.headers || {}).isToken === false

  // 是否需要防止数据重复提交

  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false

  if (config.loading) {

    showLoading()

    configCache = config

  }

  if (getToken() && !isToken) {

    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改

  }

  //请求头添加语言关键字 todo://动态获取

  config.headers['Language'] = localStorage.getItem('language') || 'zh_CN'

  //请求头添加仓库关键字 todo://动态获取

  config.headers['WarehouseId'] = localStorage.getItem('warehouseId') || ''

  // 请求头添加当前浏览器时区

  config.headers['TimeZone'] = Intl.DateTimeFormat().resolvedOptions().timeZone || ''

  // 当前所选仓库时区

  config.headers['WarehouseTimeZone'] =localStorage.getItem('timeZone') || ''

  // get请求映射params参数

  if (config.method === 'get' && config.params) {

    let url = config.url + '?' + tansParams(config.params);

    url = url.slice(0, -1);

    config.params = {};

    config.url = url;

  }

  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {

    const requestObj = {

      url: config.url,

      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,

      time: new Date().getTime()

    }

    const sessionObj = cache.session.getJSON('sessionObj')

    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {

      cache.session.setJSON('sessionObj', requestObj)

    } else {

      const s_url = sessionObj.url;                // 请求地址

      const s_data = sessionObj.data;              // 请求数据

      const s_time = sessionObj.time;              // 请求时间

      const interval = 500;                       // 间隔时间(ms),小于此时间视为重复提交

      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url && !config.noNeedDeal) {

        const message = t('oth.doNotResubmit');

        console.warn(`[${s_url}]: ` + message)

        return Promise.reject(new Error(message))

      } else {

        cache.session.setJSON('sessionObj', requestObj)

      }

    }

  }

  return config

}, error => {

    if (config.loading) {

        hideLoading()

        configCache = null

    }

    // console.log(error)

    Promise.reject(error)

})

// 响应拦截器

service.interceptors.response.use(res => {

  // 未设置状态码则默认成功状态

  const code = res.data.code || 200;

  // 获取错误信息

  const msg = errorCode[code] || res.data.msg || errorCode['default']

  // 二进制数据则直接返回

  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {

    return res.data

  }

  if (code === 401) {

    if (!isRelogin.show) {

      isRelogin.show = true;

      ElMessageBox.confirm(t('oth.loginStatusExpired'), t('common.systemTip'), {

        confirmButtonText: t('oth.loginAgain'),

        cancelButtonText: t('common.cancel'),

        type: 'warning'

      }

      ).then(() => {

        isRelogin.show = false;

        store.dispatch('LogOut').then(() => {

          location.href = '/saas-wms-web/index';

        })

      }).catch(() => {

        isRelogin.show = false;

      });

    }

    if (configCache?.loading) {

        hideLoading()

        configCache = null

    }

    return Promise.reject(t('oth.invalidSession1'))

  } else if (code === 500) {

    ElMessage({

      dangerouslyUseHTMLString: true,//将 message 属性作为 HTML 片段处理

      message: msg,

      type: 'error'

    })

    if (configCache?.loading) {

        hideLoading()

        configCache = null

    }

    return Promise.reject(new Error(msg))

  }  

  else if (code !== 200 && code !== 110) {

    ElNotification.error({

      title: msg

    })

    if (configCache?.loading) {

        hideLoading()

        configCache = null

    }

    return Promise.reject('error')

  } else {

    if (configCache?.loading) {

        hideLoading()

    }

    return Promise.resolve(res.data)

  }

},

  error => {

    console.log('err' + error)

    let { message } = error;

    if (message == "Network Error") {

      message = t('oth.backendInterCon1');

    }

    else if (message.includes("timeout")) {

      message = t('oth.sysInterfaceTimeout');

    }

    else if (message.includes("Request failed with status code")) {

      message = t('oth.interface') + message.substr(message.length - 3) + t('rma.claimOrder.exceptionCauses');

    }

    ElMessage({

      message: message,

      type: 'error',

      duration: 5 * 1000

    })

    if (configCache?.loading) {

        hideLoading()

        configCache = null

    }

    return Promise.reject(error)

  }

)

// 通用下载方法

export function download(url, params, filename, config) {

  downloadLoadingInstance = ElLoading.service({ text: i18n.global.t('common.downloadTips'), background: "rgba(0, 0, 0, 0.7)", })

  return service.post(url, params, config ?? {

    transformRequest: [(params) => { return tansParams(params) }],

    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

    responseType: 'blob'

  }).then(async (data) => {

    const isLogin = await blobValidate(data);

    if (isLogin) {

      const blob = new Blob([data])

      saveAs(blob, filename)

    } else {

      const resText = await data.text();

      const rspObj = JSON.parse(resText);

      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']

      ElMessage.error(errMsg);

    }

    downloadLoadingInstance.close();

  }).catch((r) => {

    console.error(r)

    ElMessage.error(i18n.global.t('common.downloadError'))

    downloadLoadingInstance.close();

  })

}

export default service

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值