先来看一下效果图
请求回来所有文章,根据索引进行上一篇下一篇的判断
首先为两个按钮绑定点击事件
<button
@click="last(lastId, columnId)"
:disabled="isLast"
:class="{ disClick: isLast === true }"
>
上一篇:{{ lastTitle }}
</button>
<button
:class="[nextBtn, { disClick: isNext === true }]"
@click="next(nextId, columnId)"
:disabled="isNext"
>
下一篇:{{ nextTitle }}
</button>
请求回来的所有文章为一个数组,forEach循环,找到当前文章id的索引,下一篇文章就是索引加一,上一篇文章就是索引减一,如果索引值为最后一个,下一篇按钮为禁用状态,如果索引值为最第一个,上一篇按钮为禁用状态。
getAllList(columnId.value).then((res: any) => {
console.log(res);
articleAllList.value = res.data;
console.log(articleId.value);
articleAllList.value.forEach((item: any, index) => {
if (item.id === articleId.value) {
//获取索引
console.log(index);
if (index >= articleAllList.value.length - 1) {
nextTitle.value = '无';
isNext.value = true;
} else {
nextTitle.value = articleAllList.value[index + 1].articleName;
nextId.value = articleAllList.value[index + 1].id;
}
if (index == 0) {
lastTitle.value = '无';
isLast.value = true;
} else {
lastTitle.value = articleAllList.value[index - 1].articleName;
lastId.value = articleAllList.value[index - 1].id;
}
}
});
});
最后在分别写点击事件,进行跳转
//点击上一篇文章时;
const last = (articleId: string, columnId: string) => {
router.push({
path: 'detail',
query: { articleId, columnId },
});
};
//点击下一篇文章时
const next = (articleId: string, columnId: string) => {
router.push({
path: 'detail',
query: { articleId, columnId },
});
};