h5触底加载

518 阅读1分钟
import _ from 'lodash';
data() {
  return {
    loading: false,
    form: {
      pageNo: 0,
      pageSize: 10,
    },
  eventList:[],
  totalPages: 0, // 总页数
  }
},
mounted() {
  window.addEventListener('scroll', this.throttleScroll, true);
},
beforeDestroy() {
  window.removeEventListener('scroll', this.throttleScroll);
},
methods: {
  async getEventList() {
    this.form.pageNo = this.form.pageNo + 1;
    if(this.totalPages !== 0 && this.form.pageNo > this.totalPages) return;
    this.loading = true;
    try {
      const res = await bossEventApi.eventList(this.form);
      if (res.code !== responseCode.SUCCESS) throw new Error(res.message || res.msg || '发生错误');
      const list = res.data && res.data.records
      const eventList = list || [];
      this.eventList = this.eventList.concat(eventList)
      this.totalPages = res.data.pages || 0;
    } catch (err) {
      console.error(err);
    }
    this.loading = false;
  },
  throttleScroll: _.throttle(function() {
    this.handlerScroll();
  }, 200),
  handlerScroll() {
    if(this.loading) return;
    // 当前滚动的高度(最大的时候) + 可视区高度 = 总高度
    const scrollTop = this.$refs.longList.scrollTop; // 当前滚动的高度
    const clientHeight = this.$refs.longList.clientHeight; // 可视区高度
    const scrollHeight = this.$refs.longList.scrollHeight; // 总高度
    if(scrollHeight - scrollTop - clientHeight < 200) {
      this.getEventList();
    }
  },
}