vue实战滚动加载

935 阅读1分钟

Vue的实现方式

实现需要获取三个高度 滚动容器的scrollHeight,滚动容器的可视高度clientHeight,滚动容器滚动的距离scrollTop 当scrollTop+clientHeight>=scrollHeight时,则需要重新加载

滚动加载.png

  <div class="scroll-container" @scroll="handleScroll" ref="scroll" >
      <ul>
        <li v-for="(item,index) in liData" :key="index">滚动加载</li>
      </ul>
  </div>
</template>

<script>
export default {

data() {
  return {
    liData:[1,2,3,4,5,6,7,8,9,10]
  }
},
methods: {
  handleScroll(){
    let scrollDom = this.$refs.scroll;
    let scrollTop = scrollDom.scrollTop;
    let scrollHeight = scrollDom.scrollHeight;
    let clientHeight = scrollDom.clientHeight;
    if(clientHeight+scrollTop>=scrollHeight){
      console.log("I want more")
      this.liData = this.liData.concat(this.liData)
    }
  }
},

}
</script>

<style lang="less" scoped>
ul,li{
  padding: 0;
  margin: 0;
}
li{
  list-style: none;
}
.scroll-container{
        background-color: beige;
        width: 100%;
        height: 500px;
        overflow: auto;
        li{
          height: 100px;
          width: 100%;
          background-color: antiquewhite
        }
    }
</style>