【问题标题】:I need to know how to add pagination with vue.js?我需要知道如何使用 vue.js 添加分页?
【发布时间】:2018-07-29 18:01:34
【问题描述】:

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

【问题讨论】:

    标签: node.js mongodb vue.js


    【解决方案1】:

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

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

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

    【讨论】:

    • 您不应修改计算属性中的状态或组件变量。计算属性是派生值。
    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多