列表滚动

66 阅读1分钟
<template>
  <div class="items-box">
    <div class="items2-box" @scroll="handleScroll">
      <div class="items2" v-for="item in list">
        <div>{{ item }}</div>
      </div>
    </div>
    <div class="items" v-for="item in list2">
      <div>{{ item }}</div>
    </div>

  </div>
</template>

<script lang='ts' setup>
import { onMounted, reactive, ref, toRefs } from "vue";
const list = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
const { list2 } = toRefs(reactive({ list2: [1, 2, 3, 4, 5, 6, 7, 8] }));
const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement;
  // 计算当前是滑动到哪个元素
  const index = Math.floor(target.scrollTop / 50);
  console.log("target", index);
  if (index + 8 < list.value.length) {
    list2.value = list.value.slice(index, index + 8);
  } else {
    // 如果index+8大于list的长度,就返回最后8个元素
    list2.value = list.value.slice(list.value.length - 8, list.value.length);
  }
  console.log("list2.value", list2.value);
};
onMounted(() => {
  // 初始化拿到list的前八个元素
  list2.value;
  console.log("list2", list2.value);
});
</script>
<style lang='scss' scoped>
.items-box {
  width: 200px;
  height: 400px;
  border: 1px solid #000;
  overflow: hidden;
  overflow-y: auto;
}
.items2-box {
  position: absolute;
  top: 0;
  width: 100%;
  height: 400px;
  overflow: hidden;
  overflow-y: auto;
  z-index: 9999;
  .items2 {
    width: 50px;
    opacity: 0;
    height: 50px;
  }
}
.items {
  width: 50px;
  height: 50px;
  background-color: rgb(68, 68, 169);
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
}
.items:nth-child(1) {
  transform: translate(20%, 0);
}
.items:nth-child(2) {
  transform: translate(30%, 0);
}
.items:nth-child(3) {
  transform: translate(40%, 0);
}
.items:nth-child(4) {
  transform: translate(50%, 0);
}
.items:nth-child(5) {
  transform: translate(50%, 0);
}
.items:nth-child(8) {
  transform: translate(20%, 0);
}
.items:nth-child(7) {
  transform: translate(30%, 0);
}
.items:nth-child(6) {
  transform: translate(40%, 0);
}
</style>