虚拟列表

2022-06-20

前端

我来到这个世界,为了看看太阳和蓝色的地平线。——《城门开》

分享一个vue虚拟列表的组件:

https://github.com/tangbc/vue-virtual-scroll-list

官方文档:

https://tangbc.github.io/vue-virtual-scroll-list

沙盒:

https://codesandbox.io/s/live-demo-virtual-list-e1ww1

使用方式:

1
pnpm install vue-virtual-scroll-list --save

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
<div>
<virtual-list style="height: 360px; overflow-y: auto;" // make list scrollable
:data-key="'uid'"
:data-sources="items"
:data-component="itemComponent"
/>
</div>
</template>

<script>
import Item from './Item'
import VirtualList from 'vue-virtual-scroll-list'

export default {
name: 'root',
data () {
return {
itemComponent: Item,
items: [{uid: 'unique_1', text: 'abc'}, {uid: 'unique_2', text: 'xyz'}, ...]
}
},
components: { 'virtual-list': VirtualList }
}
</script>

子组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<div>{{ index }} - {{ source.text }}</div>
</template>

<script>
export default {
name: 'item-component',
props: {
index: { // index of current item
type: Number
},
source: { // here is: {uid: 'unique_1', text: 'abc'}
type: Object,
default () {
return {}
}
}
}
}
</script>