Skip to content

Instantly share code, notes, and snippets.

@johnhalsey
Last active December 14, 2018 15:22
Show Gist options
  • Save johnhalsey/b2a3cf0d51bb5400b07eda874e71ca5c to your computer and use it in GitHub Desktop.
Save johnhalsey/b2a3cf0d51bb5400b07eda874e71ca5c to your computer and use it in GitHub Desktop.
VueJS Pagination with Bootstrap 4
<template>
<div id="url-list-table_paginate" class="dataTables_paginate paging_simple_numbers">
<ul v-if="pages" class="pagination">
<li class="paginate_button page-item previous"
:class="{'disabled': currentPage == 1}">
<a href="#"
class="page-link"
aria-controls="url-list-table"
@click.prevent="getPreviousPage">Previous</a>
</li>
<li v-for="(page, index) in range"
:key="index"
class="paginate_button page-item"
:class="{'active': currentPage == page}">
<a v-if="page != '...'"
href="#"
class="page-link"
aria-controls="url-list-table"
@click.prevent="getPage(page)">
{{page}}
</a>
<a v-else href="#" class="elipses">
{{page}}
</a>
</li>
<li class="paginate_button page-item next"
:class="{'disabled': currentPage >= pages}">
<a href="#"
class="page-link"
aria-controls="url-list-table"
@click.prevent="getNextPage">Next</a>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Pagination',
props: {
pages: {
type: Number,
default: 0
},
currentPage: {
type: Number,
default: 1
}
},
data() {
return {
range: []
}
},
computed: {
propsToWatch() {
return this.pages, this.currentPage, Date.now()
}
},
watch: {
propsToWatch: {
handler: 'organisePageLinks',
immediate: true
}
},
methods: {
organisePageLinks() {
this.range = []
for (let i = 1; i <= this.pages; i++) {
if (
i == 1 || // first page
i == this.pages || // last page
i == this.currentPage || // current page
i == this.currentPage - 1 || // page before current
i == this.currentPage + 1 || // page after current
(i <= 4 && this.currentPage < 4) || // "filler" links at start
(i >= this.pages - 3 && this.currentPage > this.pages - 3) // "filler" links at end
) {
let index = this.range.length
if (index > 0 && this.range[index - 1] < i - 1) {
// if this page is not the next one insequence, add in 3 dots "..."
this.range.push('...')
}
this.range.push(i)
}
}
},
getPage(page) {
this.$emit('page-changed', page)
},
getPreviousPage() {
this.getPage(this.currentPage - 1)
},
getNextPage() {
this.getPage(this.currentPage + 1)
}
}
}
</script>
<style type="text/css" lang="scss" scoped>
.elipses {
font-size: 1.077rem;
line-height: 18px;
font-weight: 400;
padding: 0.9692rem 0.2231rem 0.2692rem;
color: #404040;
border-radius: 2px;
margin-left: 4px;
position: relative;
display: block;
cursor: default;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment