设置一些合理的默认值。
data: ({
posts: [],
pagination: {
per: 10,
current: 0,
total: 0
}
})
现在让我们用一个简单的方法找回我们的帖子:
async getPosts() {
try {
const { data } = await axios.get('/api/posts')
this.posts = data.posts
this.pagination.total = data.posts.length
} catch (e) {
// console.log(e)
}
}
并创建一些计算属性以确定哪些应该是可见的:
computed: {
postsToShow: {
get: function() {
return this.posts.slice(current, per)
}
}
}
并更新我们的v-for:
v-for="posts in postsToShow"
现在让我们添加一个选择项来确定一次显示多少个帖子。
<select v-model="postsPerPage">
<option value="10"> 10 </option>
<option value="20"> 20 </option>
</select>
并添加适当的getter/setter
computed: {
postsPerPage: {
get: function() {
return this.pagination.per
},
set: function(per) {
this.pagination.per = per
}
}
}
以及用于循环浏览页面的按钮:
<a href="#" @click.prevent="nextPage"> Next </a>
<a href="#" @click.prevent="previousPage"> Previous </a>
及其对应的功能:
nextPage() {
this.pagination.current = (this.pagination.current * this.per < this.total) ? this.current++ : this.current
}
previousPage() {
this.pagination.current = (this.pagination.current > 0) ? this.pagination.current-- : 0
}
让我们显示用于直接导航到特定页面的按钮:
<a href="#" v-for="p in (pagination.total / pagination.per)" v-text="p" @click.prevent="setCurrent(p)"></a>
以及我们对应的方法:
setCurrent(page) {
this.paginagation.current = page
}