vue 实现loading
Vue 实现 Loading 的方法
使用 v-if 和 v-show 控制显示
在 Vue 中可以通过 v-if 或 v-show 控制 loading 组件的显示与隐藏。v-if 会动态创建或销毁组件,而 v-show 仅切换 CSS 的 display 属性。
<template>
<div>
<div v-if="isLoading" class="loading">
Loading...
</div>
<div v-else>
Content loaded!
</div>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: true
}
},
mounted() {
setTimeout(() => {
this.isLoading = false
}, 2000)
}
}
</script>
<style>
.loading {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
background: #f0f0f0;
}
</style>
使用第三方库(如 Element UI、Vant)
许多 UI 框架提供了内置的 loading 组件,例如 Element UI 的 el-loading 或 Vant 的 van-loading。
Element UI 示例:
<template>
<div v-loading="isLoading" element-loading-text="Loading...">
Content here
</div>
</template>
<script>
export default {
data() {
return {
isLoading: true
}
},
mounted() {
setTimeout(() => {
this.isLoading = false
}, 2000)
}
}
</script>
Vant 示例:
<template>
<div>
<van-loading v-if="isLoading" type="spinner" />
<div v-else>
Content loaded!
</div>
</div>
</template>
<script>
import { Loading } from 'vant'
export default {
components: {
[Loading.name]: Loading
},
data() {
return {
isLoading: true
}
},
mounted() {
setTimeout(() => {
this.isLoading = false
}, 2000)
}
}
</script>
全局 Loading 状态管理
通过 Vuex 或 Provide/Inject 实现全局 loading 状态管理,适合多个组件共享 loading 状态。
Vuex 示例:
// store.js
export default new Vuex.Store({
state: {
isLoading: false
},
mutations: {
setLoading(state, payload) {
state.isLoading = payload
}
}
})
组件中使用:
<template>
<div>
<div v-if="$store.state.isLoading" class="loading">
Loading...
</div>
<button @click="fetchData">Load Data</button>
</div>
</template>
<script>
export default {
methods: {
fetchData() {
this.$store.commit('setLoading', true)
setTimeout(() => {
this.$store.commit('setLoading', false)
}, 2000)
}
}
}
</script>
自定义 Loading 动画
可以通过 CSS 或 SVG 实现自定义 loading 动画,提升用户体验。
CSS Spinner 示例:
<template>
<div v-if="isLoading" class="spinner"></div>
</template>
<style>
.spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-left-color: #09f;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
异步请求拦截器
在 Axios 拦截器中统一处理 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)
})
总结
Vue 实现 loading 的方式多样,可以根据项目需求选择合适的方法。简单的项目可以使用 v-if 或 v-show,复杂项目推荐结合状态管理或拦截器统一处理。第三方库提供了开箱即用的解决方案,而自定义动画能提升用户体验。







