Skip to content

Instantly share code, notes, and snippets.

@timrijkse
Created January 23, 2017 11:22
Show Gist options
  • Save timrijkse/ce19c38514312e9d1ef383c2e24a88cc to your computer and use it in GitHub Desktop.
Save timrijkse/ce19c38514312e9d1ef383c2e24a88cc to your computer and use it in GitHub Desktop.
paginator mixin for vue
import clamp from 'lodash/clamp'
export default {
props: {
/**
* The items inside the paginator
*/
items: {
type: Array,
required: true
},
/**
* The amount of items per page
*/
offset: {
type: Number,
default: 1
},
/**
* Wheter the carousel should be infinite or not
*/
infinite: {
type: Boolean,
default: true
}
},
data () {
return {
cursor: 0,
direction: null
}
},
computed: {
/**
* The total amount of items
*/
total () {
return Math.ceil(this.items.length / this.offset)
},
/**
* The last page
*/
last () {
return (this.total - 1)
},
/**
* The previous page
*/
previous () {
return (this.cursor - 1)
},
/**
* The next page
*/
next () {
return (this.cursor + 1)
},
/**
* Whetere the previous button is shown or not
*/
showPreviousButton () {
if (this.infinite) {
return true
}
return (this.previous >= 0)
},
/**
* Wheter the next button is shown or not
*/
showNextButton () {
if (this.infinite) {
return true
}
return (this.next <= this.last)
}
},
methods: {
/**
* A page is requested
*/
onPaginate (page) {
if (this.infinite) {
if (page < 0) {
this.cursor = (this.total - 1)
} else {
this.cursor = Math.max(0, page % this.last)
}
return
}
this.cursor = clamp(page, 0, this.last)
},
/**
* The next page is requested
*/
onNextPage () {
this.direction = 1
this.onPaginate(this.next)
},
/**
* The previous page is requested
*/
onPreviousPage () {
this.direction = -1
this.onPaginate(this.previous)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment