vuejs如何使用v-for迭代部分数组

gil*_*usz 0 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'}
      ...
   ]
}
Run Code Online (Sandbox Code Playgroud)

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

模板1:

<template v-for="item in items">
   first 3 elements:
   {{item}}
</template>
Run Code Online (Sandbox Code Playgroud)

模板2:

<template v-for="item in items">
   the rest of elements: 
   {{item}}
</template>
Run Code Online (Sandbox Code Playgroud)

我应该如何修改我的v-for工作呢?

Tom*_*ech 7

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

<template v-for="item in items.slice(0, 3)">
Run Code Online (Sandbox Code Playgroud)

<template v-for="item in items.slice(3)">
Run Code Online (Sandbox Code Playgroud)

NB在上述两种情况下,假设items始终定义并始终为数组.如果你想使用内联方法但items可能未定义,那么你可以使用(items || []).slice().

使用计算属性方法,您可以定义类似于:

computed: {
    itemsHead() {
        return this.items ? this.items.slice(0, 3) : [];
    },
    itemsTail() {
        return this.items ? this.items.slice(3) : [];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后参考itemsHead,并itemsTail在您的模板.