使用http请求的Vue.js分页



我有一个带有分页导航组件的表:

<b-pagination-nav :link-gen="linkGen"
limit="5" :number-of-pages="10" use-router>
</b-pagination-nav>

我使用方法getTrades获取表内容,并向json API请求http:

axios.get(`http://localhost:5000/trades/page/${page}`)

其中,每个${page}都对应于某个数据片段。服务器端代码和请求工作正常。现在我想把点击按钮的页码传给方法getTrades。为此,我在linkGen方法中调用了getTrades方法。

linkGen(pageNum) {
console.log(pageNum);
this.getTrades(pageNum);
return pageNum === 1 ? '?' : `?page=${pageNum}`;
},

我从页码列表中得到随机值,而不是右边的页码。Console.log从列表中多次打印出随机值,但linkGen仍然返回页码的正确值。

编辑:添加了详细代码

模板部分:

<template>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="trades">
<table id="header-fixed" class="table table-bordered table-sm">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th>
<th scope="col">Time</th>
<th scope="col">Asset</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
<th scope="col">Operation</th>
<th scope="col">Order</th>
<th scope="col">Fee</th>
</tr>
</thead>
<tbody>
<tr v-for="(trade, index) in trades" :key="index">
<td>{{ trade.Date }}</td>
<td>{{ trade.Time }}</td>
<td>{{ trade.Asset }}</td>
<td>{{ trade.Qty }}</td>
<td>{{ trade.Price }}</td>
<td>{{ trade.Operation }}</td>
<td>{{ trade.Order }}</td>
<td>{{ trade.Fee }}</td>
</tr>
</tbody>
</table>
</div>
<div class="overflow-auto">
<b-pagination-nav :link-gen="linkGen"
limit="5" :number-of-pages="10" use-router>
</b-pagination-nav>
</div>
</div>
</div>
</div>
</template>

脚本部分:

<script>
import axios from 'axios';
export default {
data() {
return {
trades: [],
};
},
created() {
this.getTrades();
},
methods: {
getTrades(page = 1) {
axios.get(`http://localhost:5000/trades/page/${page}`)
.then((res) => {
this.trades = res.data.trades;
})
.catch((error) => {
console.error(error);
});
},
linkGen(pageNum) {
console.log(pageNum);
this.getTrades(pageNum);
return pageNum === 1 ? '?' : `?page=${pageNum}`;
},  
},
};
</script>

服务器响应示例:

{
"status": "success", 
"trades": [
{
"Asset": "GOLD-12.20", 
"Date": "15.08.2020", 
"Fee": 1.0, 
"Operation": "Sell", 
"Order": 61310215, 
"Price": 1726.8, 
"Qty": 1.0, 
"Time": "21:34:17"
}, 
{
"Asset": "GOLD-12.20", 
"Date": "15.08.2020", 
"Fee": 1.0, 
"Operation": "Buy", 
"Order": 61310216, 
"Price": 1726.8, 
"Qty": 1.0, 
"Time": "21:34:17"
}
]
}

好的,我自己找到了一个解决方案。首先,有必要使用分页而不是分页导航。并添加事件侦听器@change

<b-pagination
v-model="currentPage"
:total-rows="rows"
:per-page="perPage"
first-text="First"
prev-text="Prev"
next-text="Next"
last-text="Last"
@change="loadPage"
></b-pagination>

第二,在回调函数loadPage中,我们使用从按钮传递的页码从API获取必要的数据部分。

loadPage(pageNum) {
this.getTrades(pageNum);
},

最新更新