我在我的代码中使用了 .slice() 函数来切片我从 API 请求 (.get) 的响应中获得的 10 个元素的数组,这让我可以显示 10 个中的 9 个。
但是,我想在单击按钮时返回第 10 个元素。
例如,如果 API 请求共有 19 个元素,我将它们切片为 (0, 9),那么在单击按钮后,它应该将第 10 个元素添加到下一个 9 中,依此类推。
下面是我使用的 Javascript 代码:
getProjects: function() {
this.loading = true;
let url = this.craftURL();
axios.get(url, {
headers: {
Accept: "application/json"
}
}).then(response => {
this.loading = false;
console.log("Response", response.data)
if (response.data.projects) {
response.data.projects.project.slice(0, 9).forEach(project => {
this.projects.push(this.parseProject(project));
});
} else if (response.data.search.response) {
if (response.data.search.response.numberFound == 0) {
this.noProjects = true;
return;
}
response.data.search.response.projects.project.slice(0, 9).forEach(project => {
this.projects.push(this.parseProject(project));
});
if (this.projects.length == response.data.search.response.numberFound) {
this.hideButton = true;
return;
} else {
this.hideButton = false;
return;
}
}
}).catch(error => {
console.log(error);
});
},
this.projects 是我在数据中添加的空数组。
非常感谢!
最佳答案
我明白了,你想实现分页以减少负载。您可以设置跳过和限制并获得所需的数据量。请参阅文档以了解 skip 和 limit 的想法。
loadMore() {
this.data = {
user:this.username,
skip: this.s+=1,
limit: this.l+=1
}
this.service.getabcd(data).subscribe(x=>{
this.project=x;
}
然后在后端设置限制并像这样跳过
router.post('/abcs/', async (req, res) => {
const ab= await XYZ.find({ username: req.body['user']
}).skip(req.body.skip).limit(req.body.limit);
res.json(ab);
});
关于Javascript:返回切片元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54362901/