<template>
  <!-- 无限滚动容器，实现滚动加载 -->
  <view>
    <slot></slot>
    <view class="infinite-scroll"
          v-if="hasMore">
      <tui-loadmore v-if="isLoading"
                    text="加载中..."></tui-loadmore>
      <tui-nomore v-else-if="!isLoading"
                  text="上拉获取更多数据"></tui-nomore>
    </view>
    <tui-nomore v-else
                text="没有更多了"></tui-nomore>
  </view>
</template>
<script>
export default {
  props: {
    fetchItems: Function,
    hasMore: {
      type: Boolean,
      default: true,
    },
    initialLoad: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isLoading: false,
    };
  },
  mounted() {
    if (this.initialLoad) {
      this.loadMore();
    }
  },
  methods: {
    async loadMore() {
      if (this.isLoading) {
        return;
      }
      this.isLoading = true;
      try {
        await this.fetchItems();
      } catch (error) {
        console.log(error);
      } finally {
        this.isLoading = false;
      }
    },
    // uniapp触底钩子函数
    reachBottom() {
      if (!this.hasMore) {
        return;
      }
      this.loadMore();
    },
  },
};
</script>
