vue.js如何使用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(easy)在DOM中进行迭代,但是我想在两个模板中进行迭代-template1中数组的前3个元素和template2中其余的元素:

template1:

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

template2:

<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中的模板。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章