优化背景:如果你的应用存在非常长的或者无限滚动的列表,那么需要采用窗口化的技术来优化性能,只需要渲染少部分的内容(可视区域),减少重新渲染组件和创建dom节点的时间,可以参考以下的开源项目vue-vitual-scoll -list 和vue-virtual-scroller ,来优化这种无限列表的场景;
参考文档:https://www.npmjs.com/package/vue-virtual-scroll-list
1.安装 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>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss"></style>
<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>
效果图:
vue-virtual-scroller插件请参考:https://www.npmjs.com/package/vue-virtual-scroller
这里不再示范和赘述!!!!亲测效果,请勿随意转载!!转载注明出处~