vue 实现懒渲染
Vue 实现懒渲染的方法
懒渲染(Lazy Rendering)通常用于优化长列表或复杂组件的性能,仅在需要时渲染内容。以下是几种常见的实现方式:
使用 v-if 或 v-show 控制渲染
通过条件判断决定是否渲染组件或元素。v-if 会完全销毁和重建组件,而 v-show 仅切换 CSS 的 display 属性。
<template>
<div>
<button @click="showComponent = !showComponent">Toggle</button>
<div v-if="showComponent">
<!-- 懒渲染的内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
showComponent: false
}
}
}
</script>
使用 Intersection Observer API
通过监听元素是否进入视口实现懒渲染。适用于图片懒加载或滚动加载场景。
<template>
<div ref="lazyElement">
<!-- 内容会在进入视口后渲染 -->
</div>
</template>
<script>
export default {
mounted() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 触发渲染逻辑
observer.unobserve(entry.target);
}
});
});
observer.observe(this.$refs.lazyElement);
}
}
</script>
使用第三方库 vue-lazyload
专门用于 Vue 的懒加载库,支持图片、组件等资源的懒加载。
-
安装库:

npm install vue-lazyload -
在 Vue 中使用:
import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload, { preLoad: 1.3, attempt: 3 });
3. 在模板中应用:
```html
<img v-lazy="imageUrl">
动态组件与异步加载
结合 Vue 的异步组件和 Webpack 的代码分割功能实现懒渲染。

const LazyComponent = () => import('./LazyComponent.vue');
export default {
components: {
LazyComponent
}
}
虚拟滚动优化长列表
对于超长列表,使用虚拟滚动技术(如 vue-virtual-scroller)仅渲染可见区域内容。
-
安装库:
npm install vue-virtual-scroller -
使用示例:
<template> <RecycleScroller :items="items" :item-size="50" key-field="id" > <template v-slot="{ item }"> <!-- 渲染单个列表项 --> </template> </RecycleScroller> </template>
注意事项
- 懒渲染可能引发布局偏移(CLS),需预留占位空间。
- 频繁切换
v-if可能导致性能问题,适合渲染成本高的组件。 - 虚拟滚动需确保每项高度固定或可计算,否则需使用动态高度版本。






