在我们渲染真实数据的时候,很有可能上万条数据,如果我们都将他们渲染到我们的页面的页面当中,思考一下,他们是多么大的一个工程,大大影响到了我们项目的性能,这时候,我们就可以封装一个虚拟列表的组件,只有当到了可视化区域,这个位置的数据显现出来,这时候呢,就大大优化了我们项目的性能。具体效果如下:
当然了,我这里只是一个最基本的组件封装,样式可能有些差,所以呢,大家要想改样式,也是挺好修改的,以下是源码,供大家参考,希望对你有帮助!!!(使用的时候注意引入组件的位置哦!!!)
主组件当中引用list子组件
<template>
<div>
<!-- size:60表格高度,showNumber:10每页显示条数 -->
<List :items="list" :size="50" :showNumber="15"> </List>
</div>
</template>
<script setup lang="ts">
import {
ref,
onMounted,
} from "vue";
import List from "@/components/List.vue";
let list = ref([]);
onMounted(() => {
getList();
});
const getList = () => {
list.value = Array(5000)
.fill("")
.map((item, index) => ({
id: index,
content: "淼淼" + index,
}));
console.log(list.value);
};
</script>
<style lang="scss" scoped>
</style>
虚拟列表子组件的封装
<template>
<div>
<h1 style="text-align: center;font-size:35px">虚拟列表</h1>
<hr>
<div
class="container"
:style="{ height: containerHeight }"
@scroll="handleScroll"
ref="container"
>
<div class="list" :style="{ top: listTop }">
<div
v-for="item in showData"
:key="item.id"
:style="{ height: props.size + 'px' }"
>
<!-- 显示的内容 -->
{{ item.content }}
<hr />
</div>
<div class="bar" :style="{ height: barHeight }"></div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import {
ref,
computed,
defineProps,
} from "vue";
let props = defineProps(["items", "size", "showNumber"]);
//切片,开始和结束
let start = ref(0);
let end = ref(props.showNumber);
let container = ref(null);
let showData = computed(() => {
//在可视化区域显示得数据内容
return props.items.slice(start.value, end.value);
});
let containerHeight = computed(() => {
//可视化的高度
return props.size * props.showNumber + "px";
});
let barHeight = computed(() => {
//所有数据的高度
return props.size * props.items.length + "px";
});
let listTop = computed(() => {
//位置
return start.value * props.size + "px";
});
//当滚动条滚动时候进行触发的事件,其中对start和end进行重新赋值
let handleScroll = () => {
const scrollTop = container.value.scrollTop;
start.value = Math.floor(scrollTop / props.size);
end.value = start.value + props.showNumber;
};
</script>
<style lang="scss" scoped>
//样式
.container {
overflow-y: scroll;
background: rgb(150, 150, 150, 0.5);
font-size: 20px;
font-weight: bold;
line-height: 60px;
width: 500px;
margin: 0 auto;
position: relative;
text-align: center;
.list {
position: absolute;
top: 0;
width: 100%;
}
}
</style>
ok,今天就分享这么多啦,有好东西还会与大家分享的!!!哦豁,大家一起加油吧!!!