当前位置: 代码网 > it编程>编程语言>Javascript > vue简单实现一个虚拟列表的示例代码

vue简单实现一个虚拟列表的示例代码

2024年05月18日 Javascript 我要评论
一、前言当今的时代是大数据时代,往往一个列表就有成千上万条数据,而我们一一渲染的话,则需要耗费大量时间,导致网页打开缓慢。懒加载虽然减少了第一次渲染时间,加快了网页打开速度,但随着后续数据的不断载入拼

一、前言

当今的时代是大数据时代,往往一个列表就有成千上万条数据,而我们一一渲染的话,则需要耗费大量时间,导致网页打开缓慢。懒加载虽然减少了第一次渲染时间,加快了网页打开速度,但随着后续数据的不断载入拼接,列表的渲染时间也会越来越长。虚拟列表则很好的解决了这一问题。

虚拟列表只渲染当前可视区域的列表,并不会将所有的数据渲染。下面用vue简单实现移动端虚拟列表(并且支持下拉触底加载效果)

二、代码实现

准备下拉数据:

export default {
  data() {
    return {
      listdata: [], // 总数据
      isloading: false, // 展示loading
    };
  },
  mounted() {
    this.getlistdata();
  },
  methods: {
    // 获取数据
    getlistdata() {
      const count = 20 + this.listdata.length;
      const start = this.listdata.length;
      this.isloading = true;
      settimeout(() => {
        for (let i = start; i < count; i++) {
          this.listdata.push(i);
        }
        this.isloading = false;
      }, 500);
    },
  },
};

需要准备内外两个列表容器,外部容器(viewport)固定高度用于生成滚动条,内部容器(scrollbar)用于撑开外部容器使得滚动条保持与未使用虚拟列表时一致。

<template>
  <div class="viewport" ref="viewport">
    <!-- 滚动条 -->
    <div class="scrollbar" :style="{ height: listheight + 'px' }"></div>
    <!-- 展示的列表 -->
    <div
      class="list"
      :style="{ transform: `translatey(${transformoffset}px)` }"
    >
      <div
        class="row"
        :style="{ height: rowheight + 'px' }"
        v-for="(item, index) in showlist"
        :key="index"
      >
        <slot :record="item"></slot>
      </div>
    </div>
    <!-- 加载 -->
    <div class="loading_wrap" v-show="loading">
      <div class="loading">
        <div class="container"></div>
      </div>
      <div>正在加载中</div>
    </div>
  </div>
</template>

<style lang="less" scoped>
/*
------最外层容器---------*/
.viewport {
  width: 100%;
  height: 100%; // 这个的高度让父组件去决定
  background-color: #fff;
  position: relative;
  overflow-y: auto;
}
/*
------列表展示层容器---------*/
.list {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}
/*
------每行容器---------*/
.row {
  overflow: hidden;
}

</style>

计算列表的总高度listheight(列表的总条数乘以每一条的高度),可视区域的高度viewheight。

计算当前可见区域起始数据的startindex和结束数据的endindex,监听viewport列表滚动事件,计算currentindex以及列表的偏移量transformoffset。

监听滚动事件动态设置显示的列表(showlist)。

<script lang="ts" setup>
import {
  defineprops,
  withdefaults,
  defineemits,
  ref,
  onmounted,
  computed,
} from "vue";
interface props {
  list: string[]; // 数据源
  rowheight: number; // 每行的高度
  viewcount: number; // 显示数量
  loading: boolean; // 控制loading
}

const props = withdefaults(defineprops<props>(), {
  list: () => [],
  rowheight: 200,
  viewcount: 10,
  loading: false,
});

const emit = defineemits<{
  (e: "bottomload"): void;
}>();
let viewheight = ref(0); //可视区域的高度
let startindex = ref(0); //开始索引
let endindex = ref(0); //结束索引
let transformoffset = ref(0); //列表的偏移量
const viewport = ref(null);

onmounted(() => {
  initdata();
});
let showlist = computed(() =>
  props.list.slice(startindex.value, endindex.value)
); //展示的数据
let listheight = computed(() => props.list.length * props.rowheight); //列表的总高度

// 初始化一些数据
const initdata = () => {
  endindex.value = props.viewcount;
  viewheight.value = viewport.value.offsetheight;
};

// 列表滚动
const onscroll = () => {
  const scrolltop = viewport.value.scrolltop; // 获取试图往上滚动的高度
  const currentindex = math.floor(scrolltop / props.rowheight); // 计算当前的索引
  // 只在需要变化的时 才重新赋值
  if (startindex.value !== currentindex) {
    startindex.value = currentindex;
    endindex.value = startindex.value + props.viewcount; // 结束索引
    transformoffset.value = scrolltop - (scrolltop % props.rowheight);
  }
  // 触底了
  if (math.round(viewheight.value + scrolltop) === listheight.value) {
    // 发送触底加载事件
    emit("bottomload");
  }
};
</script>

三、完整代码

demo.vue

<template>
  <div class="page">
    <h3>长列表渲染</h3>
    <listscroll
      class="list_scroll"
      :list="listdata"
      :loading="isloading"
      @bottomload="onbottomload"
    >
      <template v-slot="{ record }">
        <div class="row_content" @click="handleclick(record)">
          <div>{{ record }}</div>
          <img
            class="image"
            src="https://gimg2.baidu.com/image_search/src=http%3a%2f%2fsafe-img.xhscdn.com%2fbw1%2f2076f7ae-d134-4dc4-a865-af1b2029d400%3fimageview2%2f2%2fw%2f1080%2fformat%2fjpg&refer=http%3a%2f%2fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1680249943&t=7646a71b62c810256a2b414e96106808"
          />
        </div>
      </template>
    </listscroll>
  </div>
</template>

<script>
export default {
  data() {
    return {
      listdata: [], // 总数据
      isloading: false, // 展示loading
    };
  },
  mounted() {
    this.getlistdata();
  },
  methods: {
    // 获取数据
    getlistdata() {
      const count = 20 + this.listdata.length;
      const start = this.listdata.length;
      this.isloading = true;
      settimeout(() => {
        for (let i = start; i < count; i++) {
          this.listdata.push(i);
        }
        this.isloading = false;
      }, 500);
    },
    // 监听触底事件
    onbottomload() {
      console.log("触底了");
      if (this.listdata.length >= 100) {
        console.log("数据加载完了~");
        return;
      }
      // 加载数据
      this.getlistdata();
    },
    // 监听点击每行
    handleclick(record) {
      console.log(record, "record");
    },
  },
};
</script>

<style lang="less" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  .list_scroll {
    flex: 1;
  }
}
.row_content {
  width: 100%;
  height: 100%;
  .image {
    display: block;
    width: 100%;
    height: 160px;
    object-fit: cover;
  }
}
</style>

listscroll.vue

<template>
  <div class="viewport" ref="viewport" @scroll="onscroll">
    <!-- 滚动条 -->
    <div class="scrollbar" :style="{ height: listheight + 'px' }"></div>
    <!-- 展示的列表 -->
    <div
      class="list"
      :style="{ transform: `translatey(${transformoffset}px)` }"
    >
      <div
        class="row"
        :style="{ height: rowheight + 'px' }"
        v-for="(item, index) in showlist"
        :key="index"
      >
        <slot :record="item"></slot>
      </div>
    </div>
    <!-- 加载 -->
    <div class="loading_wrap" v-show="loading">
      <div class="loading">
        <div class="container"></div>
      </div>
      <div>正在加载中</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  defineprops,
  withdefaults,
  defineemits,
  ref,
  onmounted,
  computed,
} from "vue";
interface props {
  list: string[]; // 数据源
  rowheight: number; // 每行的高度
  viewcount: number; // 显示数量
  loading: boolean; // 控制loading
}

const props = withdefaults(defineprops<props>(), {
  list: () => [],
  rowheight: 200,
  viewcount: 10,
  loading: false,
});

const emit = defineemits<{
  (e: "bottomload"): void;
}>();
let viewheight = ref(0); //可视区域的高度
let startindex = ref(0); //开始索引
let endindex = ref(0); //结束索引
let transformoffset = ref(0); //列表的偏移量
const viewport = ref(null);

onmounted(() => {
  initdata();
});
let showlist = computed(() =>
  props.list.slice(startindex.value, endindex.value)
); //展示的数据
let listheight = computed(() => props.list.length * props.rowheight); //列表的总高度

// 初始化一些数据
const initdata = () => {
  endindex.value = props.viewcount;
  viewheight.value = viewport.value.offsetheight;
};

// 列表滚动
const onscroll = () => {
  const scrolltop = viewport.value.scrolltop; // 获取试图往上滚动的高度
  const currentindex = math.floor(scrolltop / props.rowheight); // 计算当前的索引
  // 只在需要变化的时 才重新赋值
  if (startindex.value !== currentindex) {
    startindex.value = currentindex;
    endindex.value = startindex.value + props.viewcount; // 结束索引
    transformoffset.value = scrolltop - (scrolltop % props.rowheight);
  }
  // 触底了
  if (math.round(viewheight.value + scrolltop) === listheight.value) {
    // 发送触底加载事件
    emit("bottomload");
  }
};
</script>

<style lang="less" scoped>
/*
------最外层容器---------*/
.viewport {
  width: 100%;
  height: 100%; // 这个的高度让父组件去决定
  background-color: #fff;
  position: relative;
  overflow-y: auto;
}
/*
------列表展示层容器---------*/
.list {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}
/*
------每行容器---------*/
.row {
  overflow: hidden;
}
/*
------loading样式---------*/
.loading_wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  padding: 20px 0;
  .loading {
    box-sizing: border-box;
    width: 20px;
    height: 20px;
    border: 2px solid #ddd;
    border-radius: 50%;
    animation: rotate 1s linear infinite;
    margin-right: 10px;
  }
  .container {
    position: relative;
    top: 50%;
    left: 50%;
    width: 10px;
    height: 10px;
    background-color: #fff;
  }
}
/*
------loading动画---------*/
@keyframes rotate {
  from {
    transform-origin: center center;
    transform: rotate(0deg);
  }
  to {
    transform-origin: center center;
    transform: rotate(360deg);
  }
}
</style>

四、实现效果

五、实现效果

实现虚拟列表就是处理滚动条滚动后的可见区域的变更,具体实现步骤如下:

  • 计算当前可见区域起始数据的startindex
  • 计算当前可见区域借宿数据的endindex
  • 计算当前可见区域的数据,并渲染到页面中
  • 计算startindex对应的数据在整个列表中的偏移位置transformoffset,并设置到列表上

到此这篇关于vue简单实现一个虚拟列表的示例代码的文章就介绍到这了,更多相关vue 虚拟列表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com