article.vue 2.24 KB
<template>
  <Article ref="article" :on-fetch="onFetch" @on-follow="onFollow">
    <template v-slot:thumb>
      <ArticleItem v-for="data in currentList" :key="data.articleId" :data="data"></ArticleItem>
    </template>
  </Article>
</template>

<script>
import {get} from 'lodash';
import Article from './components/article/article';
import ArticleItem from './components/article/article-item';
import {createNamespacedHelpers} from 'vuex';
const {mapState, mapActions, mapMutations} = createNamespacedHelpers('article');

export default {
  name: 'ArticlePage',
  data() {
    return {
      page: 1,
      id: 0
    };
  },
  created() {
    this.id = this.$route.params.id;
  },
  serverPrefetch() {
    return this.onFetch();
  },
  beforeRouteUpdate(to, from, next) {
    if (this.$route.params.id !== to.params.id) {
      this.id = to.params.id;
      this.init();
    }
    next();
  },
  computed: {
    ...mapState(['articleList']),
    currentList() {
      if (this.articleList.length > 2) {
        return this.articleList.slice(0, 2);
      }
      return this.articleList;
    }
  },
  methods: {
    ...mapMutations(['CHANGE_AUTHOR_FOLLOW']),
    ...mapActions(['fetchArticleList']),
    init() {
      this.page = 1;
      this.$refs.article.init();
    },
    async onFetch() {
      if (this.page === 1 && this.articleList.length) {
        this.page++;
        return this.articleList;
      }
      const articleId = parseInt(this.id, 10);

      if (!articleId) {
        return;
      }
      const result = await this.fetchArticleList({
        articleId,
        page: this.page
      });

      if (result.code === 200) {
        if (get(result, 'data.detailList', []).length) {
          this.page++;
          return Promise.resolve(result.data.detailList);
        }
        return Promise.resolve(false);
      } else {
        this.$createToast && this.$createToast({
          txt: result.message || '服务器开小差了',
          type: 'warn',
          time: 1000
        }).show();
      }
    },
    onFollow({authorUid, follow}) {
      this.CHANGE_AUTHOR_FOLLOW({authorUid: authorUid, follow});
    }
  },
  components: {
    Article,
    ArticleItem
  }
};
</script>

<style lang="scss" scoped>
.article-page {
  background-color: #f0f0f0;
}
</style>