英文:
laravel vue inertia paginator remove prev and next links
问题
I'm trying to remove prev and next links from an array using Laravel Vue 3 InertiaJS. Here's the code I have:
const splicedlinks = computed(() => {
let prevIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("« Previous");
let nextIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("Next »");
props.links.meta.links.splice(prevIndex, 1);
props.links.meta.links.splice(nextIndex, 1);
return props.links.meta.links;
});
With this code, I managed to remove "« Previous," but not "Next »." What's wrong with my code?
英文:
Im trying to remove prev and next links from array. Using laravel vue3 inertiajs.
const splicedlinks = computed(() => {
let prevIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("« Previous");
let nextIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("Next »");
props.links.meta.links.splice(prevIndex, 1);
props.links.meta.links.splice(nextIndex, 1);
return props.links.meta.links;
});
With this code i managed only to remove "« Previous", but not "Next »"
Whats wrong with my code?
i explained what i tried in question.
答案1
得分: 1
因为第一次使用 "splice" 后,"Next" 元素的索引已更改。
JS Array 的 splice 方法会影响源数组。因此,在用 "splice" 方法删除元素后,找到的元素索引就不相关了。
在用 "prevIndex" 删除元素后,你应该找到 "nextIndex"。
尝试这样做:
const splicedlinks = computed(() => {
let prevIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("« Previous");
// 删除 "Previous" 按钮
props.links.meta.links.splice(prevIndex, 1);
// 在删除 "Previous" 按钮后找到 "Next" 按钮的索引
let nextIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("Next »");
// 删除 "Next" 按钮
props.links.meta.links.splice(nextIndex, 1);
return props.links.meta.links;
});
此外,你可以通过使用 "findIndex" 方法而不是 indexOf 来简化代码。
示例:
let nextIndex = props.links.meta.links?.findIndex((link) => link.label === "Next »");
英文:
Because the index of the "Next" element was changed after the first "splice" using.
JS Array splice method affects the source array. So the found elements indexes are not relevant after deleting an element by "splice" method.
You should to find "nextIndex" after deleting an element by "prevIndex"
Try this:
const splicedlinks = computed(() => {
let prevIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("« Previous");
// Remove "Previous" button
props.links.meta.links.splice(prevIndex, 1);
// After "Previous" button deleting find index of "Next" button
let nextIndex = props.links.meta.links
.map((link) => link.label)
.indexOf("Next »");
// Remove "Next" button
props.links.meta.links.splice(nextIndex, 1);
return props.links.meta.links;
});
Also, you can simplify your code by using "findIndex" methods instead indexOf
Example:
let nextIndex = props.links.meta.links?.findIndex((link) => link.label === "Next »");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论