Skip to content

Instantly share code, notes, and snippets.

@sadhakbj
Created April 18, 2020 05:55
Show Gist options
  • Select an option

  • Save sadhakbj/12965e04354eb98ed787ac5b7798077c to your computer and use it in GitHub Desktop.

Select an option

Save sadhakbj/12965e04354eb98ed787ac5b7798077c to your computer and use it in GitHub Desktop.
Pagination with laravel and vue
<template>
<nav v-if="pagination">
<ul class="pagination">
<li class="page-item" :class="{'disabled' : pagination.currentPage === 1}">
<a class="page-link" href="#" @click.prevent="changePage(pagination.currentPage - 1)">Previous</a>
</li>
<li v-for="page in pagesNumber" class="page-item"
:class="{'active': page == pagination.current_page}">
<a href="javascript:void(0)" @click.prevent="changePage(page)" class="page-link">{{ page }}</a>
</li>
<li class="page-item" :class="{'disabled': pagination.currentPage === pagination.last_page }">
<a class="page-link" href="#" @click.prevent="changePage(pagination.currentPage + 1)">Next</a>
</li>
<span style="margin-top: 8px;"> &nbsp; <i>Displaying {{ pagination.per_page }} of {{ pagination.total }} entries.</i></span>
</ul>
</nav>
</template>
<script>
export default {
props: {
pagination: {
type: Object,
required: true
},
offset: {
type: Number,
default: 4
}
},
computed: {
pagesNumber() {
if (!this.pagination.to) {
return [];
}
let from = this.pagination.current_page - this.offset;
if (from < 1) {
from = 1;
}
let to = from + (this.offset * 2);
if (to >= this.pagination.last_page) {
to = this.pagination.last_page;
}
let pagesArray = [];
for (let page = from; page <= to; page++) {
pagesArray.push(page);
}
return pagesArray;
}
},
methods: {
changePage(page) {
this.pagination.current_page = page;
this.$emit('paginate');
}
}
}
</script>
@sadhakbj
Copy link
Copy Markdown
Author

Usage in another component:

<template>
  <paginate :pagination="newsList" @paginate="fetchData" :offset="4"></paginate>
</template>

<script>
   methods: {
            async fetchData() {
                const news = await axios.get(`top-headlines?page=${this.newsList.current_page}&country=${this.country}&source_id=${this.source_id}`)
                this.newsList = news.data
            }
        }
</script>

The data format:

{
"current_page": 1,
"data": [],
"first_page_url": "http://newstask.test/top-headlines?page=1",
"from": 1,
"last_page": 10,
"last_page_url": "http://newstask.test/top-headlines?page=10",
"next_page_url": "http://newstask.test/top-headlines?page=2",
"path": "http://newstask.test/top-headlines",
"per_page": 10,
"prev_page_url": null,
"to": 10,
"total": 100
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment