Vue.js vuejs如何使用v-for仅迭代数组的一部分
我有一个数组,如下所示:Vue.js vuejs如何使用v-for仅迭代数组的一部分,vue.js,vuejs2,Vue.js,Vuejs2,我有一个数组,如下所示: return { items: [ {active: true, text: 'text1'}, {active: true, text: 'text2'}, {active: true, text: 'text3'}, {active: true, text: 'text4'}, {active: true, text: 'text5'} ... ] } 我想使用v-for(简单)在
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中的其余元素:
<template v-for="item in items">
the rest of elements:
{{item}}
</template>
模板1:
<template v-for="item in items">
first 3 elements:
{{item}}
</template>
前3个要素:
{{item}}
模板2:
<template v-for="item in items">
the rest of elements:
{{item}}
</template>
其余要素:
{{item}}
我应该如何修改我的
v-for
来实现这一点?您可以基于原始项
数组显式创建两个计算属性,或者只使用一个切片,例如:
<template v-for="item in items.slice(0, 3)">
然后在模板中参考
itemsHead
和itemsTail
。我刚刚想出了另一个解决方案,如果你有一个稍微复杂的对象,例如,如果你有一个外循环和一个内循环,你只想在条件为真的情况下渲染一些东西,而你不能像在一个内循环中那样使用计算方法。如果循环内的计算方法不是这样,请纠正我
因此,我的解决方案如下:
<div v-for="fooparent in fooparentarray">
<template v-for="foo in fooparent.foos">
<div v-if="foo.someproperty === 1">{{foo.someproperty}}</div>
</template>
</div>
{{foo.someproperty}
由于未渲染模板,因此不会为不满足条件的阵列元素渲染任何内容。因此,只有满足条件时才会呈现div。
返回此项。
必须是在三元表达式中返回此.items.length
,因为!![]
是真的
。或者您是否要检查此.items是否为未定义的?@conneso您是对的。这与v-for=“items.slice(0,3)中的item”相同,但Tom的回答是正确的,因为我的数组将至少有3个元素。如果愿意,您可以改进答案:)@connexo唯一的问题是当此项不是数组时。如果它是一个空数组,那么这不是问题。然后使用array.isArray(this.items)
,因为这也会澄清其意图。是的,或者检查属性切片是否存在并且是一个函数,或者如果它是一个道具,那么指定类型:array
,但我不确定其中任何一个是否在范围内:)
<div v-for="fooparent in fooparentarray">
<template v-for="foo in fooparent.foos">
<div v-if="foo.someproperty === 1">{{foo.someproperty}}</div>
</template>
</div>