vue滚动加载

299 阅读1分钟

使用 vue 实现一个滚动加载的功能

贴代码:

<template>
  <div class="box">
    <ul ref="list" @scroll="scrollLoad">
      <li v-for="n in list" :key="n">
        {{ n }}
      </li>
      <li v-if="showText">我是有底线的</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: 10,
      showText: false
    }
  },
  methods: {
    scrollLoad() {
      let scrollTop = this.$refs.list.scrollTop   // 滚动条距离盒子顶部距离
      let boxHeight = this.$refs.list.offsetHeight    // 盒子(可视区)高度
      let scrollHeight = this.$refs.list.scrollHeight   // 滚动高度
      if(this.list >= 20) {
        this.showText = true
      }else {
        if(boxHeight >= scrollHeight - scrollTop - 5) {
          this.list += 2
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  ul {
    width: 300px;
    height: 180px;
    overflow: auto;
    border: 1px solid #ddd;
    li {
      height: 20px;
      text-align: center;
    }
  }
}
</style>

效果: