vue实现页面加载
Vue 实现页面加载的方法
在 Vue 中实现页面加载效果可以通过多种方式完成,以下是一些常见的方法:
使用 v-if 或 v-show 控制加载状态
通过数据绑定控制加载状态的显示与隐藏,适用于简单的加载效果。
<template>
<div>
<div v-if="isLoading">加载中...</div>
<div v-else>页面内容</div>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: true
}
},
mounted() {
setTimeout(() => {
this.isLoading = false
}, 2000)
}
}
</script>
使用异步组件和 Suspense
Vue 3 提供了 Suspense 组件,可以更好地处理异步加载状态。

<template>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<div>加载中...</div>
</template>
</Suspense>
</template>
<script>
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
import('./AsyncComponent.vue')
)
export default {
components: {
AsyncComponent
}
}
</script>
使用路由导航守卫
在 Vue Router 中可以通过全局前置守卫实现页面加载效果。
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
router.beforeEach((to, from, next) => {
showLoading()
next()
})
router.afterEach(() => {
hideLoading()
})
function showLoading() {
// 显示加载动画
}
function hideLoading() {
// 隐藏加载动画
}
使用第三方加载组件

可以集成第三方库如 Element UI、Ant Design Vue 等提供的加载组件。
<template>
<div>
<a-spin v-if="loading" />
<div v-else>内容</div>
</div>
</template>
<script>
import { Spin } from 'ant-design-vue'
export default {
components: {
'a-spin': Spin
},
data() {
return {
loading: true
}
}
}
</script>
骨架屏技术
使用骨架屏提升用户体验,在内容加载前显示页面结构轮廓。
<template>
<div>
<div v-if="loading" class="skeleton">
<div class="skeleton-header"></div>
<div class="skeleton-body"></div>
</div>
<div v-else>
<!-- 实际内容 -->
</div>
</div>
</template>
<style>
.skeleton {
/* 骨架屏样式 */
}
</style>
性能优化建议
- 对于首屏加载,可以考虑使用服务端渲染(SSR)或静态站点生成(SSG)
- 合理使用代码分割和懒加载,减少初始加载体积
- 预加载关键资源,提升用户体验
- 使用 CDN 加速静态资源加载
- 优化图片和其他媒体资源大小
每种方法都有其适用场景,可以根据项目需求选择最合适的实现方式。






