仅v-for循环数组与动态页码相对应

时间:2019-03-26 06:57:21

标签: vue.js vue-component

我按页码存储结果,请参见下文

<ul v-for="iten in listingsData" :key="item.id">
    <li>{{ item.name }}</li>
</ul>
<button @click="pushPrev">Push Prev Results</button>
<button @click="pushNext">Push Next Results</button>

export default {
    data(){
        return {
            listingsData : [],
            page : 1
        }
    },
    methods : {
        pushNext(){
            var _self = this;
            axios.get('https://myapi.com/get/users?page='+this.page+1).then(function(response){
                _self.page = _self.page + 1;
                _self.listingsData = _self.listingsData.push({
                    page : _self.page,
                    results : response.data.results

                })

            });    
        },
        pushPrev(){
            var _self = this;
            axios.get('https://myapi.com/get/users?page='+this.page-1).then(function(response){
                _self.page = _self.page + 1;
                _self.listingsData = _self.listingsData.push({
                    page : _self.page,
                    results : response.data.results
                })

            });    
        }
    }
    created(){
        //load default data
        var _self = this;
        axios.get('https://myapi.com/get/users?page='+this.page).then(function(response){
            _self.listingsData = {
                page : 1,
                results : response.data.results

            }
        });    
    }
}

现在如何显示或循环显示仅与页码this.page相对应的结果?

_self.listingsData = _self.listingsData.push({
    page : _self.page, // page number
    results : response.data.results
})

有什么帮助,有想法吗?

PS:我正在使用Vue CLI,Webpack

1 个答案:

答案 0 :(得分:0)

您应该遍历将返回listingsData中特定页面而不是所有页面的计算属性。

类似的东西:

<template>
  <div v-if="currentPage">
    <ul v-for="item in currentPage.results" :key="item.id">
      <li>{{ item.name }}</li>
    </ul>
  </div>
  <div v-else><i>Loading...</i></div>

  <button @click="fetchPage(-1)" :disabled="page===1">Prev Results</button>
  <button @click="fetchPage(1)" :disabled="page===10">Next Results</button>
</template>

<script>
const api = "https://myapi.com/get/users";
export default {
  data() {
    return {
      page: 1,
      listingsData: [],
    };
  },
  created() {
    this.fetchPage(0);
  },
  computed: {
    currentPage() {
      return this.listingsData.find(i => i.page === this.page);
    },
  },
  methods: {
    fetchPage(diff) {
      this.page += diff;
      if (this.currentPage) {
        return; // page already loaded
      }
      const page = this.page;
      axios.get(api, { params: { page } })
           .then((res) => {
             this.listingsData.push({
               page,
               results: res.data.results,
             });
           });
    },
  }
};
</script>

在这里,我们仅在之前未加载页面的情况下才加载页面,如果当前页面分别为1/10,则禁用上一页/下一页按钮。

这里是jsfiddle(带有模型数据而不是实际的API调用)。