vue实现页面加载弹窗
Vue 实现页面加载弹窗的方法
使用 Vue 组件和状态管理
创建一个独立的弹窗组件(如 LoadingPopup.vue),通过 v-if 或 v-show 控制显示。结合 Vuex 或 props 传递加载状态。
<template>
<div class="loading-popup" v-if="isLoading">
<div class="spinner"></div>
<p>加载中...</p>
</div>
</template>
<script>
export default {
props: {
isLoading: Boolean
}
}
</script>
<style>
.loading-popup {
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;
z-index: 1000;
}
.spinner {
/* 添加加载动画样式 */
}
</style>
在父组件中控制弹窗
通过父组件的 data 或方法控制弹窗显示,适合简单场景。
<template>
<div>
<button @click="fetchData">加载数据</button>
<LoadingPopup :isLoading="isLoading" />
</div>
</template>
<script>
import LoadingPopup from './LoadingPopup.vue'
export default {
components: { LoadingPopup },
data() {
return {
isLoading: false
}
},
methods: {
async fetchData() {
this.isLoading = true
try {
await axios.get('/api/data')
} finally {
this.isLoading = false
}
}
}
}
</script>
使用第三方库
例如 element-ui 的 Loading 组件,直接调用封装好的方法。
import { Loading } from 'element-ui'
// 显示加载
let loadingInstance = Loading.service({ fullscreen: true })
// 关闭加载
loadingInstance.close()
全局加载状态管理
通过 Vuex 集中管理加载状态,适合复杂应用。
// store.js
export default new Vuex.Store({
state: {
isLoading: false
},
mutations: {
setLoading(state, payload) {
state.isLoading = payload
}
}
})
<!-- 组件中使用 -->
<template>
<LoadingPopup :isLoading="$store.state.isLoading" />
</template>
<script>
export default {
methods: {
async loadData() {
this.$store.commit('setLoading', true)
await fetchData()
this.$store.commit('setLoading', false)
}
}
}
</script>
路由切换时的加载弹窗
使用 Vue Router 的导航守卫触发全局加载状态。
router.beforeEach((to, from, next) => {
store.commit('setLoading', true)
next()
})
router.afterEach(() => {
store.commit('setLoading', false)
})






