vue 实现loading
Vue 实现 Loading 的方法
使用 v-if 和 v-show 控制显示
在 Vue 中可以通过 v-if 或 v-show 控制 Loading 组件的显示与隐藏。定义一个布尔值变量 isLoading,在异步操作开始和结束时切换状态。
<template>
<div>
<div v-if="isLoading" class="loading">Loading...</div>
<button @click="fetchData">Load Data</button>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false
}
},
methods: {
async fetchData() {
this.isLoading = true
try {
await this.$http.get('/api/data')
} finally {
this.isLoading = false
}
}
}
}
</script>
<style>
.loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
color: white;
}
</style>
使用第三方库
可以使用第三方库如 vue-loading-overlay 或 element-ui 的 Loading 组件快速实现。
安装 vue-loading-overlay:
npm install vue-loading-overlay
使用示例:
<template>
<div>
<loading :active.sync="isLoading" :can-cancel="false"></loading>
<button @click="fetchData">Load Data</button>
</div>
</template>
<script>
import Loading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.css'
export default {
components: {
Loading
},
data() {
return {
isLoading: false
}
},
methods: {
async fetchData() {
this.isLoading = true
try {
await this.$http.get('/api/data')
} finally {
this.isLoading = false
}
}
}
}
</script>
全局 Loading 状态管理
对于大型应用,可以通过 Vuex 管理全局 Loading 状态。
定义 Vuex store:
// store.js
export default new Vuex.Store({
state: {
isLoading: false
},
mutations: {
setLoading(state, isLoading) {
state.isLoading = isLoading
}
}
})
在组件中使用:
<template>
<div>
<div v-if="$store.state.isLoading" class="loading">Loading...</div>
<button @click="fetchData">Load Data</button>
</div>
</template>
<script>
export default {
methods: {
async fetchData() {
this.$store.commit('setLoading', true)
try {
await this.$http.get('/api/data')
} finally {
this.$store.commit('setLoading', false)
}
}
}
}
</script>
使用路由守卫实现页面切换 Loading
在路由切换时显示 Loading,可以通过路由守卫实现。
// router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
routes: [...]
})
router.beforeEach((to, from, next) => {
store.commit('setLoading', true)
next()
})
router.afterEach(() => {
setTimeout(() => {
store.commit('setLoading', false)
}, 500)
})
export default router
使用动画增强体验
为 Loading 添加动画效果可以提升用户体验。
<template>
<div v-if="isLoading" class="loading">
<div class="spinner"></div>
</div>
</template>
<style>
.loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.spinner {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
以上方法可以根据具体需求选择适合的实现方式。对于简单场景,使用 v-if 或 v-show 即可;对于复杂应用,建议使用状态管理或第三方库。







