<template>
  <div class="refresh-container">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" style="margin-top:5px">
        <slot name="data"></slot>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
export default {
  name: 'Refresh',
  props: {
    page: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      limit: 10,
      alist: [],
      loading: false, // 是否正在加载下一页数据
      finished: false, // 所有数据是否加载完毕
      isLoading: false // 是否正在下拉刷新
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 封装获取文章列表数据的方法
    async getData(isRefresh) {
      await this.$emit('getData', res => {
        // 拼接列表数据
        if (isRefresh) {
          this.isLoading = false
          // 下拉刷新
          this.alist = res
        } else {
          this.loading = false
          // 上拉加载
          this.alist = [...this.alist, ...res]
        }
        this.$emit('update:list', this.alist)
        if (res.length === 0) {
          // 证明没有下一页数据了
          this.finished = true
        }
      })
    },

    // 上拉加载
    onLoad() {
      this.loading = true
      console.log('触发了 load 事件！')
      this.$emit('update:page', this.page + 1)
      this.getData()
    },
    // 下拉刷新
    onRefresh() {
      this.isLoading = true
      console.log('触发了下拉刷新！')
      this.$emit('update:page', 1)
      this.getData(true)
    }
  }
}
</script>

<style lang="scss" scoped>
.refresh-container {
  padding: 0px 0 10px 0;
}
</style>
