vue 怎么实现loading
实现 Loading 的方法
在 Vue 中实现 Loading 效果可以通过多种方式完成,以下是几种常见的方法:
全局 Loading 组件
创建一个全局的 Loading 组件,通过 Vuex 或事件总线控制其显示与隐藏。在需要的地方调用相应的方法即可。
// Loading.vue
<template>
<div v-if="isLoading" class="loading-overlay">
<div class="loading-spinner"></div>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false
}
},
methods: {
show() {
this.isLoading = true
},
hide() {
this.isLoading = false
}
}
}
</script>
使用第三方库
许多第三方库如 element-ui、vant 等提供了现成的 Loading 组件,可以直接使用。
// 使用 element-ui 的 Loading
import { Loading } from 'element-ui'
let loadingInstance = Loading.service({ fullscreen: true })
// 关闭 Loading
loadingInstance.close()
路由守卫中实现 Loading
在路由切换时显示 Loading,确保页面加载完成后再隐藏。
// router.js
router.beforeEach((to, from, next) => {
store.commit('setLoading', true)
next()
})
router.afterEach(() => {
store.commit('setLoading', false)
})
HTTP 拦截器中实现 Loading
在发送 HTTP 请求时显示 Loading,请求完成后隐藏。
// axios 拦截器
axios.interceptors.request.use(config => {
store.commit('setLoading', true)
return config
})
axios.interceptors.response.use(response => {
store.commit('setLoading', false)
return response
}, error => {
store.commit('setLoading', false)
return Promise.reject(error)
})
自定义 Loading 动画
可以通过 CSS 或 SVG 实现自定义的 Loading 动画,增强用户体验。
.loading-spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 4px solid #3498db;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
结合异步操作
在异步操作如 async/await 中控制 Loading 的显示与隐藏。

methods: {
async fetchData() {
this.isLoading = true
try {
const response = await axios.get('/api/data')
this.data = response.data
} catch (error) {
console.error(error)
} finally {
this.isLoading = false
}
}
}
通过以上方法,可以根据具体需求在 Vue 项目中灵活实现 Loading 效果。






