我有一个数组如下:
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) : [];
}
}
然后引用
itemsHead
和 itemsTail
在您的模板中。
关于vue.js - vuejs如何使用v-for只迭代数组的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48987214/