vue虚拟列表面试题

文章介绍了在前端处理大量数据时,如何使用Vue.js实现虚拟滚动来优化性能。通过设定盒子和每条数据的高度,计算可显示的最大数据量,并监听滚动事件,动态更新开始和结束的下标,从而只渲染可视区域内的数据。这种方法可以有效减少内存消耗和提升页面流畅性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设给你10万条数据前端怎么展示

  • 思路

1.已知展示数据盒子的高度,和每条数据的高度,就能知道盒子最多能展示多少条数据
2.假设盒子高度为100px,每条数据高度为2px;那么 盒子最多展示50条数据,就可以知道开始下标为0,结束下标为50
3. 监听盒子的scroll滚动事件 得到滚出的距离 滚动的距离除以 数据的高度 就能得到滚动了几条数据
4. 新的开始下标就等于滚动的距离除以每条数据的高度
5. 结束下标就等于开始下标加上50
6. 实际渲染的数据 = 原始数据.slcie(开始下标,结束下标)

  • 具体代码思路

父组件

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App" :arr="arr"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  computed:{
    arr(){
      return Array(1000).fill('').map((item,index)=>({
        id:index,
        content:'数据'+index
      }))
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

子组件

<template>
  <div class="hello" @scroll="handleScroll" ref="scroll" style="position:relative"> 
    <div style="position:absolute" :style="{top:lisTtop}">
      <div v-for="item in list" :key="item.index" style="height:20px;"  >
       {{ item.content }}
      </div>
    </div>
    <!-- 撑开盒子的高度等于原始数据的长度乘以每条数据的固定高度  我这里直接写死 因为为传入了1000条数据,每条数据的高度为20 -->
     <div style="height:20000px"></div>
  </div>
</template>

<script>

export default {
  name: 'HelloWorld',
  props: {
    msg: String,
    arr:{
      type:Array,
      default:()=>{
        return []
      }
    }
  },
  computed:{
    list(){
      return this.arr.slice(this.start,this.end)
    },
    lisTtop(){
      return this.start*20+'px'
    }
  },  
  data(){
    return{
      start:0,
      end:10,
      height:20,//每条数据的高度
    }
  },
  methods:{
    handleScroll(){
      this.start = Math.floor(this.$refs.scroll.scrollTop/this.height) //得到滚出条数据的开始下标
      //结束下标就等于 开始下标加上固定展示数量的和
      this.end = this.start + 10
      console.log(this.start,this.end,this.list)

    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello{
  height:200px;
  width:100px;
  border:1px solid red;
  overflow: hidden;
  overflow-y: scroll;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正函数 

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值