vue实现首页分屏加载
Vue 实现首页分屏加载的方法
分屏加载(Lazy Loading)可以优化首页性能,按需加载内容。以下是几种实现方式:
使用 v-if 或 v-show 控制显示
通过监听滚动事件或使用 Intersection Observer API,动态控制组件渲染:
<template>
<div>
<section v-if="showSection1">
<!-- 第一屏内容 -->
</section>
<section v-if="showSection2">
<!-- 第二屏内容 -->
</section>
</div>
</template>
<script>
export default {
data() {
return {
showSection1: true,
showSection2: false
};
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
this.showSection2 = window.scrollY > window.innerHeight;
}
}
};
</script>
使用 Vue 异步组件 + Webpack 代码分割
结合 Webpack 的动态导入功能,实现按需加载组件:
// router.js 中配置路由懒加载
const Home = () => import('./views/Home.vue');
const Section1 = () => import('./components/Section1.vue');
const Section2 = () => import('./components/Section2.vue');
const routes = [
{ path: '/', component: Home, children: [
{ path: 'section1', component: Section1 },
{ path: 'section2', component: Section2 }
]}
];
使用 Intersection Observer API
更高效的滚动监听方案,避免频繁触发事件:
export default {
data() {
return {
isVisible: false
};
},
mounted() {
const observer = new IntersectionObserver((entries) => {
this.isVisible = entries[0].isIntersecting;
});
observer.observe(this.$el);
}
};
结合 vue-lazyload 插件
适用于图片或模块的懒加载:
-
安装插件:
npm install vue-lazyload -
配置使用:
import VueLazyload from 'vue-lazyload'; Vue.use(VueLazyload, { preLoad: 1.3, attempt: 3 });
// 模板中使用
注意事项
- 分屏加载需考虑 SEO 影响,关键内容建议直接渲染。
- 移动端需测试滚动性能,避免卡顿。
- 可结合骨架屏(Skeleton)提升用户体验。







