vue 怎么实现loading
实现全局 Loading 的方法
在 Vue 中可以通过拦截 HTTP 请求和响应实现全局 Loading 效果。使用 axios 拦截器结合 Vuex 状态管理是常见方案。
// axios 拦截器配置
axios.interceptors.request.use(config => {
store.commit('SET_LOADING', true)
return config
})
axios.interceptors.response.use(
response => {
store.commit('SET_LOADING', false)
return response
},
error => {
store.commit('SET_LOADING', false)
return Promise.reject(error)
}
)
组件级 Loading 实现
通过 v-if 指令控制 Loading 组件的显示隐藏,结合异步操作的状态管理。
<template>
<div>
<loading-spinner v-if="isLoading" />
<content-component v-else />
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false
}
},
methods: {
async fetchData() {
this.isLoading = true
try {
await api.getData()
} finally {
this.isLoading = false
}
}
}
}
</script>
使用第三方库
Element UI 等组件库提供现成的 Loading 组件和服务调用方式。
// 服务方式调用
import { Loading } from 'element-ui'
let loadingInstance = Loading.service(options)
loadingInstance.close()
// 组件方式使用
<el-button
type="primary"
:loading="true"
>
加载中
</el-button>
路由级别 Loading
通过路由守卫实现页面切换时的 Loading 效果。
router.beforeEach((to, from, next) => {
store.commit('SET_PAGE_LOADING', true)
next()
})
router.afterEach(() => {
setTimeout(() => {
store.commit('SET_PAGE_LOADING', false)
}, 500)
})






