01-vue项目之滚动加载数据

  最近刚结束了一个vue项目,项目中发现了自己很多问题,例如,看到功能就想要使用插件,(⊙o⊙)…,这样是肯定不行呀,哎,用插件可以,自己也得会写呀,现在就记录一下一个不错的滚动加载数据。

  1.页面布局(重点是 class="listWrapper" 以及 class="list")

      <div class="listWrapper" ref="list_c">
        <ul class="list" v-if="collectlist && collectlist.length>0" ref="list">
          <li v-for="(item,index) of collectlist" :key="index">
            <router-link :to="{name:'detail',query:{goods_sku_id:item.goods_sku_id}}">
              <div class="picture">
                <img :src="item.image">
              </div>
              <div class="info-content">
                <p class="pro-tit">{{item.name}}</p>
                <p class="price">
                  <span>¥{{item.price}}</span>
                  <span class="old-price">¥{{item.ot_price}}</span>
                </p>
                <p class="count">已售{{item.sales_num}}件</p>
              </div>
            </router-link>
            <div class="collection-delete" @click="delect(item)"></div>
          </li>
        </ul>
      </div>

  2.样式

.listWrapper { 
position: absolute; 
top: 0.88rem; 
 100%;
 bottom: 0; 
overflow-y: auto; 
} 
.list {
 background-color: #fff;
 }

  3.js

  data数据

data() {
     return {
        page: 1, 
        pagesize: 8, 
        collectlist: [], 
        canscroll: true, 
        activeisload: true 
    }; 
}                

  在mounted钩子中添加监听器(addEventListener)

  mounted() {
    let list_c = this.$refs.list_c;
    list_c.addEventListener("scroll", () => {
      if (this.canscroll) {
        //是否具有触发条件
        let scroll_top = list_c.scrollTop;
        let list = this.$refs.list;
        let list_height = parseInt(getComputedStyle(list).height);
        
        let c_height = parseInt(getComputedStyle(list_c).height);
        if (list_height - (scroll_top + c_height) < 200) {
          this.canscroll = false; //锁定滚动触发条件
          if (this.activeisload) {
            this.page++;
            this.getCollect();
          } else {
            console.log("已加载完所有已收藏的商品");
          }
        }
      }
    });
  }

  请求接口数据(this.$post是封装的方法,自行代入实际场景)

    getCollect: function() {
      this.$post(url, {
        page: this.page,
        pagesize: this.pagesize
      })
        .then(res => {
          if (res.code == 200) {
            if (res.data.length) {
              this.collectlist = this.collectlist.concat(res.data);
              if (res.data.length < this.pagesize) {
                this.activeisload = false;
                console.log("已加载完");
              } else {
                this.canscroll = true;
              }
            }
          }
        })
        .catch();
    },
原文地址:https://www.cnblogs.com/zero18/p/10956741.html