大家好,我是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!
关注我,原创文章第一时间推送, 点赞和收藏就是最大的支持❤️