以 Vue 3 项目为例,多个请求下如何全局封装 Loading 的展示与关闭?其中大有学问!

图片

大家好,我是CodeQi! 

项目开发中,Loading 的展示与关闭是非常关键的用户体验设计。

当我们的应用需要发起多个异步请求时,如何有效地管理全局 Loading 状态,保证用户在等待数据加载时能有明确的反馈,这是一个值得深入探讨的问题。

本文将以 Vue 3 项目为例,详细讲解如何全局封装 Loading 的展示与关闭。

一、准备工作

首先,我们需要创建一个新的 Vue 3 项目。如果你还没有安装 Vue CLI,请先安装:

npm install -g @vue/cli

然后创建并进入新项目:

vue create loading-demo
cd loading-demo

确保你的项目中已经安装了 Vue 3 和 Vue CLI。

我们将使用 <script setup> 的写法来实现全局 Loading 组件。

二、封装全局 Loading 组件

1. 创建全局 Loading 组件

首先,我们在 src/components 目录下创建一个名为 GlobalLoading.vue 的组件文件:

<!-- src/components/GlobalLoading.vue -->
<template>
  <div v-if="visible" class="global-loading">
    <div class="spinner"></div>
  </div>
</template>

<script setup>
import { ref }from'vue'

// 定义一个可响应的变量来控制 Loading 的可见性
const visible =ref(false)

// 导出显示和隐藏 Loading 的方法
exportconstshowGlobalLoading=()=>{ visible.value=true}
exportconsthideGlobalLoading=()=>{ visible.value=false}
</script>

<style scoped>
.global-loading {
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
display: flex;
justify-content: center;
align-items: center;
background:rgba(255,255,255,0.8);
z-index:9999;
}
.spinner{
border:4px solid rgba(0,0,0,0.1);
border-left-color:#22a6b3;
border-radius:50%;
width:40px;
height:40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0%{
transform:rotate(0deg);
}
100%{
transform:rotate(360deg);
}
}
</style>

2. 在 main.js 中注册全局组件

我们需要在项目入口文件 main.js 中注册全局 Loading 组件:

// src/main.js
import{ createApp }from'vue'
importAppfrom'./App.vue'
importGlobalLoading,{ showGlobalLoading, hideGlobalLoading }from'./components/GlobalLoading.vue'

const app =createApp(App)

// 注册全局组件
app.component('GlobalLoading',GlobalLoading)

app.mount('#app')

export{ showGlobalLoading, hideGlobalLoading }

3. 在 App.vue 中使用全局 Loading 组件

在 src/App.vue 文件中,我们可以使用封装好的全局 Loading 组件:

<!-- src/App.vue -->
<template>
<div id="app">
<h1>Vue 3 Global Loading Example</h1>
<GlobalLoading />
<button @click="fetchData">Fetch Data</button>
</div>
</template>

<script setup>
import { showGlobalLoading, hideGlobalLoading }from'./main.js'
import axios from'axios'

// 模拟数据请求
constfetchData=async()=>{
try{
showGlobalLoading()
// 模拟多个请求
const requests =[
      axios.get('https://jsonplaceholder.typicode.com/posts/1'),
      axios.get('https://jsonplaceholder.typicode.com/posts/2')
]
awaitPromise.all(requests)
}catch(error){
console.error(error)
}finally{
hideGlobalLoading()
}
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

三、使用 Axios 拦截器处理全局 Loading 状态

当我们的应用中有多个请求时,可以通过 Axios 拦截器来自动处理全局 Loading 的展示与关闭。

1. 配置 Axios 拦截器

在 src 目录下创建一个名为 axios.js 的文件:

// src/axios.js
import axios from'axios'
import{ showGlobalLoading, hideGlobalLoading }from'./main.js'

// 请求计数器
let requestCount =0

constshowLoading=()=>{
if(requestCount ===0){
showGlobalLoading()
}
  requestCount++
}

consthideLoading=()=>{
  requestCount--
if(requestCount ===0){
hideGlobalLoading()
}
}

// 请求拦截器
axios.interceptors.request.use(
config =>{
showLoading()
return config
},
error =>{
hideLoading()
returnPromise.reject(error)
}
)

// 响应拦截器
axios.interceptors.response.use(
response =>{
hideLoading()
return response
},
error =>{
hideLoading()
returnPromise.reject(error)
}
)

exportdefault axios

2. 在 App.vue 中使用配置好的 Axios

在 src/App.vue 文件中,我们可以使用配置好的 Axios 进行数据请求:

<!-- src/App.vue -->
<template>
<div id="app">
<h1>Vue 3 Global Loading with Axios Interceptors</h1>
<GlobalLoading />
<button @click="fetchData">Fetch Data</button>
</div>
</template>

<script setup>
import axios from'./axios.js'

// 模拟数据请求
constfetchData=async()=>{
try{
// 模拟多个请求
const requests =[
      axios.get('https://jsonplaceholder.typicode.com/posts/1'),
      axios.get('https://jsonplaceholder.typicode.com/posts/2')
]
awaitPromise.all(requests)
}catch(error){
console.error(error)
}
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

四、优化和拓展

1. 优化 Loading 组件

我们可以对 Loading 组件进行一些优化,例如增加自定义颜色和大小的支持:

<!-- src/components/GlobalLoading.vue -->
<template>
  <div v-if="visible" class="global-loading">
    <div :class="spinnerClass" :style="spinnerStyle"></div>
  </div>
</template>

<script setup>
import { ref, computed }from'vue'

// 定义一个可响应的变量来控制 Loading 的可见性
const visible =ref(false)
const color =ref('#22a6b3')
const size =ref('40px')

// 导出显示和隐藏 Loading 的方法
exportconstshowGlobalLoading=(spinnerColor = '#22a6b3', spinnerSize = '40px')=>{
  color.value= spinnerColor
  size.value= spinnerSize
  visible.value=true
}
exportconsthideGlobalLoading=()=>{ visible.value=false}

const spinnerClass =computed(() =>({
spinner:true
}))

const spinnerStyle =computed(() =>({
borderColor:`rgba(0, 0, 0, 0.1)`,
borderLeftColor: color.value,
width: size.value,
height: size.value
}))
</script>

<style scoped>
.global-loading {
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
display: flex;
justify-content: center;
align-items: center;
background:rgba(255,255,255,0.8);
z-index:9999;
}
.spinner{
border:4px solid;
border-radius:50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0%{
transform:rotate(0deg);
}
100%{
transform:rotate(360deg);
}
}
</style>

2. 在请求中使用自定义颜色和大小

在 src/App.vue 文件中,我们可以使用自定义颜色和大小的全局 Loading 组件:

<!-- src/App.vue -->
<template>
  <div id="app">
<h1>Vue3CustomizableGlobalLoadingExample</h1>
<GlobalLoading />
<button @click="fetchData">FetchData</button>
</div>
</template>

<script setup>
import axios from './axios.js'
import{ showGlobalLoading, hideGlobalLoading } from './main.js'

// 模拟数据请求
const fetchData = async ()=>{
try{
    showGlobalLoading('#e74c3c','60px')
// 模拟多个请求
const requests =[
      axios.get('https://json

placeholder.typicode.com/posts/1'),
      axios.get('https://jsonplaceholder.typicode.com/posts/2')
]
    await Promise.all(requests)
}catch(error){
    console.error(error)
} finally {
    hideGlobalLoading()
}
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

五、总结

以上便是我对如何在 Vue 3 项目中封装多个请求下全局 Loading 展示与关闭的一些心得与体会。

希望能够帮助到正在学习和使用 Vue 3 的你。如果有任何疑问或建议,欢迎与我交流。


祝你编码愉快!Happy coding!

关注我,原创文章第一时间推送, 点赞和收藏就是最大的支持❤️

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeQi技术小栈

喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值