首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我需要知道如何使用vue.js添加分页?

我需要知道如何使用vue.js添加分页?
EN

Stack Overflow用户
提问于 2018-07-30 02:01:34
回答 1查看 429关注 0票数 0

我有html+javascript,要求从mongodb数据库的一些游戏(游戏1,2,3,4,5,6)只是简单的数据库与许多游戏。我想知道如何通过vue.js进行分页,每页显示4个游戏。

代码语言:javascript
复制
const SEARCH = new Vue({
el: '#search',
data: {
    query: {
        name: '',
        max_price:0,
        game_category:'',
        game_publisher:'',


    },
    games: [] // current list of games. we re-fill this array after search
},
methods: {
    btn_search: function () {
        // now we know that this.query is our search critearia object
        // so we can do fetch, and will do.

        fetch('/search?json=' + JSON.stringify(this.query))
            .then((response) => { //as you remember - res is a buffer.
                return response.text();
            })
            .then((text_response) => {
                console.log('got response!');
                let games_from_server = JSON.parse(text_response);

                this.games.splice(0, this.games.length); //it will remove all elemtns from array remove all elemtns from array

                // and add games from server one by one.
                for (let i = 0; i < games_from_server.length; i++) {
                    this.games.push(games_from_server[i]);
                }

            });



       console.log(this.query);
    }

}

});

console.log('pew?');

EN

回答 1

Stack Overflow用户

发布于 2018-07-30 03:28:53

如果你想进行客户端分页,你可以这样做:

在数据中添加currentPage: 1gamesPerPage

代码语言:javascript
复制
data() {
   return {
      currentPage: 1,
      gamesPerPage: 4,
      games: []
   }
}

然后添加一个计算属性paginatedGames,它是您的games属性拆分成页面,一个currentPageGames属性,用于过滤当前页面中的游戏,以及changePage方法,用于更改您的页面:

代码语言:javascript
复制
computed: {
   paginatedGames() {
      let page = 1;
      return [].concat.apply(
         [], 
         this.games.map( (game, index) => 
            index % this.gamesPerPage ? 
               [] : 
               { page: page++, games: this.games.slice(index, index + this.gamesPerPage)}
         )
       );
   },
   currentPageGames() {
      let currentPageGames = this.paginatedGames.find(pages => pages.page == this.currentPage);
        return currentPageGames ? currentPageGames.games : [];
   }
},
methods {
   changePage(pageNumber) {
      if(pageNumber !== this.currentPage)
           this.currentPage = pageNumber;
   }
}

完整示例:http://jsfiddle.net/eywraw8t/217989/

但是,如果您的数据库中有许多游戏,那么实现服务器端分页并仅为请求的页面获取游戏可能是一个更好的主意。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51583101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档