优化背景:如果你的应用存在非常长的或者无限滚动的列表,那么需要采用窗口化的技术来优化性能,只需要渲染少部分的内容(可视区域),减少重新渲染组件和创建dom节点的时间,可以参考以下的开源项目vue-vitual-scoll -list 和vue-virtual-scroller ,来优化这种无限列表的场景;
参考文档:https://www.npmjs.com/package/vue-virtual-scroll-list
image1.安装 cnpm/npm install vue-virtual-scroll-list --save
2.引入下载好的组件,并注册组件 import virtualList from 'vue-virtual-scroll-list'
3.注意版本1.x和2.x使用方式不同、api也不同
使用方式:
<template>
<div>
<virtual-list style="height: 360px; 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";
export default {
components: { "virtual-list": virtualList },
name: "HelloWorld",
props: {
msg: String,
},
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>
<template>
<!-- 显示的数据源 -->
<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
效果图:
imagevue-virtual-scroller插件请参考:https://www.npmjs.com/package/vue-virtual-scroller
网友评论