0👍
✅
Use a computed
property to keep track what should be visible on the current page.
With a computed
property you can easily introduce a filter on the items. Then just create the functions that sets the current page, and BAM – a paginated view of items.
The snippet below does all this, and also gives the ability to choose how many items should be visible on a given page.
Advice:
new Vue({
el: "#app",
data() {
return {
posts: [],
currentPage: 1,
postsPerPage: 10,
}
},
computed: {
// computed property to set the items visible on current page
currentPagePosts() {
return this.posts.slice((this.currentPage - 1) * this.postsPerPage, this.currentPage * this.postsPerPage)
}
},
methods: {
// pagination function
setCurrentPage(direction) {
if (direction === -1 && this.currentPage > 1) {
this.currentPage -= 1
} else if (direction === 1 && this.currentPage < this.posts.length / this.postsPerPage) {
this.currentPage += 1
}
}
},
// fetching example data (200 post-like items)
async mounted() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos')
this.posts = await response.json()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="setCurrentPage(-1)">PREV</button>
<button @click="setCurrentPage(1)">NEXT</button><br /> Current page / max page: {{ currentPage }} / {{ Math.ceil(posts.length / postsPerPage) }}<br />
<label>Set posts per page: <input v-model="postsPerPage" type="text" /></label>
<hr />
<!-- the v-for only lists items from the computed property -->
<div v-for="post in currentPagePosts" :key="post.id">
ID: {{ post.id }} Title: {{ post.title }}
</div>
</div>
Source:stackexchange.com