如何添加vue.js分页?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (95)

我有一个html+javascript请求,来自MongoDB数据库的一些游戏(game1,2,3,4,5,6)只是简单的数据库,有很多游戏。我想知道如何通过vue.js进行分页,每页显示4个游戏。?

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?');

提问于
用户回答回答于

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

在数据中添加currentPage: 1gamesPerPage:

data() {
   return {
      currentPage: 1,
      gamesPerPage: 4,
      games: []
   }
}

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

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/

但如果你的数据库有很多游戏,最好是实现服务器端分页并只为请求的页面获取游戏。

扫码关注云+社区

领取腾讯云代金券