拉取歷史記錄,並在前端做無限下拉展示,是一個非常常見的使用場景。
最近在使用的 Vant (輕量、可靠的移動端 Vue 組件庫),實現起來就非常方便。
模板實現代碼
<div id="app" v-cloak>
<van-list
v-model="loading"
:finished="finished"
finished-text="暫無更多數據"
@load="load_more_items"
>
<van-cell
v-for="item in items"
:key="item"
:title="item.name"
:value="item.created_at"
/>
</van-list>
</div>
Vue.js 實現代碼
new Vue({
el: '#app',
data: {
items: [],
finished: false,
loading: false,
offset: 0,
page: 0,
limit: 10,
},
mounted: function() {
this.fetch_items();
},
methods: {
load_more_items: function() {
this.page += 1;
this.offset = this.limit * this.page;
this.fetch_items();
},
fetch_items: function() {
var that = this;
$.ajax({
url: `/api/get_items?offset=${this.offset}&limit=${this.limit}`,
type: 'get',
dataType: 'json',
success: function(data) {
that.loading = false;
if (data.data.length) {
that.items.push(...data.data);
} else {
that.finished = true;
}
}
});
}
}
});