我遇到了一个我无法解决的奇怪问题。我想在 for-each 循环中添加 index
数字,并在我的 vue.js 组件中添加总数据计数。我设法做到了这一点,但我的计数器在分页内的每个页面上都会重置,并且 items.lenght
只计算当前分页页面的数据。我做了以下事情:
<tr v-for="(item, index) in items" v-bind:key="item.id">
<td>{{index + 1}}</td>
<td>{{item.name}}</td>
</tr>
并计算所有数据:
<div class="form-group">
Total data: {{items.length}}
</div>
第一页分页一切正常,但是当我选择第二页时,它只计算该特定页面的总数据,并且计数器再次从 1 开始。为了说明,在第一页上它显示我总共有 15 个数据(我有大约 300 个),并且索引很好:
如果我转到第二页,它仍然显示相同的总数,并且索引再次从 1 开始,我希望它继续(例如 16、17..)
部分 Vue.js 组件:
mounted() {
this.getStatuses();
this.getSchoolYears();
if (this.items.length == 0) {
this.loadPage(this.pagination.current_page);
this.getObjects();
}
},
methods: {
getSaveStateConfig() {
return {
'cacheKey': 'ApplicationComponent',
};
},
addFilter(key, value) {
this.filters = this.filters.filter(function (obj) {
return obj.key !== key;
});
this.pagination.current_page = 1;
this.filters.push({key: key, value: value});
},
loadPageDebounce: _.debounce(function (page, parameters) {
this.loadPage(page);
}, 500),
loadPage(page, parameters) {
var parameters = '';
this.filters.forEach(function (obj, index) {
parameters = parameters + '&' + obj.key + '=' + obj.value;
});
var $this = this;
axios({
method: 'GET',
url: '/api/applications?page=' + page + parameters,
headers: {'X-CSRF-TOKEN': window.csrfToken, 'X-Requested-With': 'XMLHttpRequest'},
})
.then(function (response) {
// console.log('resposne', response);
$this.items = response.data.data
$this.pagination.total = response.data.total;
$this.pagination.last_page = response.data.last_page;
$this.pagination.current_page = response.data.current_page;
$this.pagination.from = response.data.from;
$this.pagination.to = response.data.to;
$this.pagination.next_page_url = response.data.next_page_url;
$this.pagination.prev_page_url = response.data.prev_page_url;
})
.catch(function (error) {
console.log(error);
});
},
loadData() {
this.loadPage(this.pagination.current_page, this.filters);
},
如何在使用 vue.js 分页时防止这种情况发生。所有帮助表示赞赏。
最佳答案
我想这不是最好的解决方案,但它应该可以作为快速修复。
<tr v-for="(item, index) in items" v-bind:key="item.id">
<td>{{(pagination.current_page*15)-15 + index+1}}</td>
<td>{{item.name}}</td>
</tr>
将更好的解决方案编辑为计算函数以分离 View 和逻辑:
<tr v-for="(item, index) in items" v-bind:key="item.id">
<td>{{getOverallIndex(index)}}</td>
<td>{{item.name}}</td>
</tr>
computed: {
getOverallIndex: function(index) {
return this.pagination.current_page*15)-15 + index + 1
}
}
关于javascript - Vue.js 在每个页面上重置索引和长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853986/