我有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?');
答案 0 :(得分:0)
如果要进行客户端分页,则可以采用以下方式:
在数据中添加currentPage: 1
和gamesPerPage
:
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/
但是,如果您的数据库中有很多游戏,那么最好实现服务器端分页并仅针对请求的页面获取游戏。