如果你的應(yīng)用存在非常長或者無限滾動的列表屏鳍,那么需要采用 窗口化 的技術(shù)來優(yōu)化性能勘纯,只需要渲染少部分區(qū)域的內(nèi)容,減少重新渲染組件和創(chuàng)建 dom 節(jié)點的時間钓瞭〔底瘢可用到如下插件vue-virtual-scroll-list
如下是要展示無限列表的組件頁面
<template>
<div>
<virtual-list
style="height: 660px; overflow-y: auto;"
:data-key="'id'"
:data-sources="items"
:data-component="itemComponent"
/>
</div>
</template>
<script>
import virtualList from "vue-virtual-scroll-list";
import Item from "./Item"; //真正展示內(nèi)容的組件,要傳給virtualList
export default {
components: { virtualList },
name: "HelloWorld",
data() {
return {
itemComponent: Item,
items: [],
};
},
methods: {
dataSource() {
for (let i = 1; i <= 900000; i++) {
this.items.push({
id: i,
name: i + "模擬字段",
});
}
},
},
created() {
this.dataSource();
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
如下是展示單獨數(shù)據(jù)行的組件
<template>
<!-- 顯示的數(shù)據(jù)源 -->
<div>{{ index }} - {{ source.name }}</div>
</template>
<script>
export default {
name: "item-component",
props: {
index: { //每個組件的唯一索引
// index of current item
type: Number,
},
source: { //每個組件接收到的值
// here is: {id: '1', name: 'abc'}
type: Object,
default() {
return {};
},
},
},
};
</script>
image.png
原理:
他只渲染keeps傳入的個數(shù)山涡,滾動時通過改變padding的值來模擬滾動堤结,里面的每一個item在滾動時動態(tài)替換里面的值。代碼內(nèi):通過:data-sources來傳入要展示的數(shù)據(jù)的數(shù)組鸭丛。通過 :data-component來傳入要展示的組件竞穷。在組件內(nèi)通過props,來接收index(索引)和source(接收到的值)進(jìn)行展示 。
image.png
效果如下:
image.png