前言

大家好,我是麦洛,平时我们在开发中,前端请求后台接口时,​​loading​​效果是经常用到的。为了使用方便,我想将此功能封装成一个工具类,经过一番努力,成功实现了想要的效果。现在总结一下,希望帮到有需要的伙伴

解决方案

1.工具类

import Vue from 'vue'

// loading框设置局部刷新,且所有请求完成后关闭loading框
let loading
let needLoadingRequestCount = 0 // 声明一个对象用于存储请求个数
function startLoading (targetdq) {
loading = Vue.prototype.$loading({
lock: true,
text: '努力加载中...',
background: 'rgba(255,255,255,.4)',
target: document.querySelector(targetdq) // 设置加载动画区域
})
}

function endLoading () {
loading.close()
}
export function showFullScreenLoading (targetdq) {
if (needLoadingRequestCount === 0) {
startLoading(targetdq)
}
needLoadingRequestCount++
}
export function hideFullScreenLoading () {
if (needLoadingRequestCount <= 0) return
needLoadingRequestCount--
if (needLoadingRequestCount === 0) {
endLoading()
}
}

export default {
showFullScreenLoading,
hideFullScreenLoading
}

2.引入

在需要使用加载效果的页面引入方法

import { showFullScreenLoading, hideFullScreenLoading } from '@/utils/loading';

3.使用

handleCollect(modelId){
showFullScreenLoading();
requestTools.post(addApplyUrl, {modelId:modelId}).then(res => {
if (res.data.code === 0) {
this.$message.success('加入成功');
hideFullScreenLoading();
}
})
}

效果图

奥利给! loading效果这么搞真的太棒了_开发语言