vue实现页面分段加载
Vue 实现页面分段加载的方法
使用 Intersection Observer API 监听元素进入视口
通过 Intersection Observer API 可以检测目标元素是否进入视口,触发加载逻辑。适合实现无限滚动或懒加载。
// 组件内实现示例
export default {
data() {
return {
observer: null,
loadedSections: []
}
},
mounted() {
this.observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const sectionId = entry.target.dataset.section
this.loadSection(sectionId)
this.observer.unobserve(entry.target)
}
})
}, { threshold: 0.1 })
document.querySelectorAll('[data-section]').forEach(el => {
this.observer.observe(el)
})
},
methods: {
loadSection(id) {
// 模拟异步加载
setTimeout(() => {
this.loadedSections.push(id)
}, 500)
}
}
}
结合路由的懒加载
对于SPA应用,可以使用Vue Router的懒加载特性实现路由级别的分段加载。
const router = new VueRouter({
routes: [
{
path: '/heavy-component',
component: () => import('./HeavyComponent.vue') // 懒加载
}
]
})
动态组件按需加载
通过 Vue 的 <component :is=""> 结合动态导入,实现组件级别的按需加载。
<template>
<div>
<button @click="loadComponent">加载组件</button>
<component :is="currentComponent" v-if="currentComponent" />
</div>
</template>
<script>
export default {
data() {
return {
currentComponent: null
}
},
methods: {
async loadComponent() {
this.currentComponent = await import('./HeavyComponent.vue')
}
}
}
</script>
数据分块加载
对于大数据列表,可以结合分页或虚拟滚动技术实现数据的分段加载。
<template>
<div>
<div v-for="item in visibleItems" :key="item.id">{{ item.text }}</div>
<div v-if="hasMore" ref="loader">加载更多...</div>
</div>
</template>
<script>
export default {
data() {
return {
allItems: [], // 全部数据
visibleItems: [], // 当前显示数据
chunkSize: 20,
currentIndex: 0
}
},
computed: {
hasMore() {
return this.currentIndex < this.allItems.length
}
},
mounted() {
this.loadNextChunk()
this.setupObserver()
},
methods: {
loadNextChunk() {
const nextChunk = this.allItems.slice(
this.currentIndex,
this.currentIndex + this.chunkSize
)
this.visibleItems = [...this.visibleItems, ...nextChunk]
this.currentIndex += this.chunkSize
},
setupObserver() {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting && this.hasMore) {
this.loadNextChunk()
}
})
observer.observe(this.$refs.loader)
}
}
}
</script>
骨架屏优化体验
在内容加载前显示骨架屏,提升用户体验。
<template>
<div>
<div v-if="loading" class="skeleton">
<!-- 骨架屏内容 -->
</div>
<div v-else>
<!-- 实际内容 -->
</div>
</div>
</template>
注意事项
- 合理设置 Intersection Observer 的 threshold 值,避免过于敏感
- 移动端需要考虑网络状况,可以增加加载失败的重试机制
- 对于重要内容,可以优先加载或预加载
- 配合 Vue 的 keep-alive 缓存已加载组件,避免重复加载







