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

标签 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 在 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/

相关文章:

javascript - Vue.js:为其他组件管理 JS 的最佳实践

vue.js - Vue : Limit characters in text area input, 截断过滤器?

javascript - Vuejs 从 $on 事件调用方法

vue.js - VueJs : Form handling with Vuex and inputs generated with an API

javascript - 将图像与作为属性传入的对象中的 url 绑定(bind)

javascript - Vue 在开发模式下编译这个 HTML 模板非常慢

javascript - 如何在Vue中从父组件引用子组件

javascript - VueJS 2 模板

vue.js - Vue3 单文件组件中元素上存在 css 类导致添加到 dom 时渲染失败,无效的 VNode 类型 : Symbol()

javascript - 我可以让一个属性在 vue v-for 中只出现一次吗