0

我有从 mongodb 数据库请求一些游戏(游戏 1、2、3、4、5、6)的 html+javascript,只是带有很多游戏的简单数据库。我想知道如何通过 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?');

4

1 回答 1

0

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

在您的数据中添加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/

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

于 2018-07-29T19:28:53.343 回答