如何实现全局loading

点击按钮requestLoading发请求时,并没有进行loading的操作,因多个组件会在同一个页面中,为了不让每次发请求的时候都去改loading的状态,那么loading该在哪里改呢

<template>
  <div v-loading="loading">
    <el-button type="primary" @click="requestLoading">请求</el-button>
    <span class="ml-10">isLoading:{{  loading }}</span>
    <div class="flex"></div>
  </div>

</template>

<script setup lang="ts">
import { ref } from 'vue';
import { loading } from './loading';
import { request } from './request';
const list = ref([]);
async function requestLoading() {
  Promise.all([
    request('http://localhost:3000/get/user?1'),
    request('http://localhost:3000/get/user?2'),
    request('http://localhost:3000/get/user?3'),
  ]).then(([res1,res2,res3]) => {
    list.value = [res1,res2,res3]
    console.log(res1,res2,res3)
  })
}
</script>

我们在request里面改,request.ts的代码如下

import { request } from '@/utils/request';
import axios from 'axios';
import  { loading } from './loading';

const axiosInstance = axios.create()

export async function request(url:string) {
  try {
    loading.value = true
    return await axiosInstance.get(url)
  } finally {
    loading.value = false
  }
}

那么在多个请求并发的时候如何去处理loading,loading.ts的代码如下:

import { loading } from './loading';
import { ref,computed} from 'vue'

//1.loading什么时候为true //有请求的时候就发
//2.loading什么时候为false //请求已经没有了,请求的数量为0的时候

// export const loading = ref(false)

const _loadingCount = ref(0)

export const loading = computed({
  get() {
    //_loadingCount 的值大于 0,loading 就会返回 true,表示有请求正在进行
    return _loadingCount.value > 0
  },
  //这个计算属性是基于 _loadingCount 这个响应式变量来计算的。
  set(val) {
    //则 _loadingCount 的值会增加 1,表示有一个新的请求开始了;如果 val 为 false,则 _loadingCount 的值会减少 1,表示有一个请求结束了。
    _loadingCount.value += val ? 1 : -1
    _loadingCount.value = Math.max(0,_loadingCount.value)
  }
})

那么在点击按钮的时候,在所有的请求完成后loading才结束

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容