gpt4 book ai didi

vue.js - vuejs如何使用v-for只迭代数组的一部分

转载 作者:行者123 更新时间:2023-12-03 06:43:02 25 4
gpt4 key购买 nike

我有一个数组如下:

return {
items: [
{active: true, text: 'text1'},
{active: true, text: 'text2'},
{active: true, text: 'text3'},
{active: true, text: 'text4'},
{active: true, text: 'text5'}
...
]
}

我想使用 v-for 在 DOM 中迭代它(简单)但我想在两个模板中迭代它们 - template1 中数组的前 3 个元素和 template2 中的其余元素:

模板1:
<template v-for="item in items">
first 3 elements:
{{item}}
</template>

模板2:
<template v-for="item in items">
the rest of elements:
{{item}}
</template>

我应该如何修改我的 v-for使这项工作?

最佳答案

您可以基于原始 items 显式创建两个计算属性。数组,或者只使用一个切片,例如:

<template v-for="item in items.slice(0, 3)">


<template v-for="item in items.slice(3)">

注意在上述两种情况下,均假设 items总是被定义并且总是一个数组。如果你想使用内联方法但是 items可能未定义,那么您可以使用 (items || []).slice() .

使用计算属性方法,您可以定义如下内容:
computed: {
itemsHead() {
return this.items ? this.items.slice(0, 3) : [];
},
itemsTail() {
return this.items ? this.items.slice(3) : [];
}
}

然后引用 itemsHeaditemsTail在您的模板中。

关于vue.js - vuejs如何使用v-for只迭代数组的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48987214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com