[Vuejs]-How to do pagination in vuejs

2đź‘Ť

âś…

For real pagination you will need to ensure that your endpoints (from your post I’d say something like /candidates) will return json AND that it will return a pagniated object ofcourse.

In Laravel you’d do it like

public function index() {
   return Candidates::paginate(10);
}

EDIT: for more information regarding laravel pagination you can take a look at their examples and docs: https://laravel.com/docs/5.4/pagination

A full example is rather hard to give but here a really short one

routes/web.php

Route::get('candidates', 'CandidateController@index');

app/http/controller/CandidateController

public function index() {
    $candidates = App\Candidate::paginate(10);

    return $candidates;
}

For a more detailed version of the laravel part you should provide your Controller, Migration, Routing setup.

In Vue I’d suggest you load all your data from within Vue and not with blade. Even though you could keep it as it is – it would be more “unified”.

data: function() {
   return { paginator: null }
},
created: function() {
   // load initial first 10 entries
   axios.get('/candidates').then(function(response) {
      this.paginator = response.data;
   }.bind(this));
}

Ok so now you have the initial load as you had it before. You can loop through pagniator.data which is your actual list now. Small example:

<ul v-if="paginator"><!-- important !not loaded on initial render-->
   <li v-for="paginator.data as candidate">{{ candidate.name }}</li>
</ul>

Now to the load more. Let’s say you want a button for that. The paginator has a pro called next_page_url to give you the next http endpoint. If it’s null – now data is left to load.

<button v-if="paginator && paginator.next_page_url" @click.prevent="loadMore">Load more</button>

Button is setup – now the load more

methods: {
    loadMore: function() {
        // load next 10 elements
        axios.get(this.paginator.next_page_url).then(function(response) {
            // you have two options now. Either replace the paginator fully - then you will actually "page" your results. 
            // only 10 will be visible at any time
            this.paginator = response.data;
        }.bind(this));
    }
}

There you go this is an actual pagination. If you want to loadMore to add 10 elements to your current list it is a little bit more tricky because you don’t want to replace the paginator.data with the new loaded stuff. You want to concat it.

...
axios.get(this.paginator.next_page_url).then(function(response) {
  response.data.data = this.paginator.data.concat(response.data.data);
  this.paginator = response.data;
}.bind(this));
👤Frnak

Leave a comment