【问题标题】:Vue. How can I get prev and current value in loop v-for for comparing it?Vue。如何在循环 v-for 中获取 prev 和 current 值以进行比较?
【发布时间】:2021-09-19 22:03:58
【问题描述】:

我有一部分结构:

....
<template v-for="(item, INDEX) in someList">
    <template v-if="thisIsArrayList(item)">
        <template v-for="(_item) in item">
            <Component
                :item="_item"
                :key="_item.id"
                :myprop="checkIndex(INDEX)" - makes here some manipulation with prev and current INDEX and return iterration++ 0, 1
            ></Component>
        </template>
    </template>
    <template v-else>
        ....
    </template>
</template>
....

INDEX 可以多次使用相同的值,例如 (22, 22, 22) 下一步,例如 (25, 25) 等等.. 所以我尝试在 props:arrayId 中将 prevINDEXcurrentIndex 进行比较,以便通过迭代++ 将其传递给子项,就像新值一样

例如:

INDEX 几次等于 22 --> 将其更改为 0 并返回此值 --> 下一个 INDEX 夫妇时间等于 55 --> 将其更改为 1 并返回此值 --> 依此类推...

如何在 Vue 中做到这一点? 或者也许这个逻辑有另一种解决方案?

谢谢。

【问题讨论】:

  • 你的问题有点不清楚; the index v-for parameter 有帮助吗?例如。 v-for="(item, index) in items" 将使循环中的模板访问索引值,您可以使用它来访问 items 中的上一个和/或下一个值。
  • 我编辑了这个例子..所以你可以看到我的意思是什么 INDEX

标签: javascript vue.js vue-component v-for vue-props


【解决方案1】:

您不需要使用显式变量事实上 v-for 本身为您提供了在迭代期间提取索引的能力

<template v-for="(item, index) in items">
    <Component
        :item="item"
        :key="item.id"
    ></Component>
</template>

根据上面的代码,arrayId 属性不是必需的,因为您不再要比较索引 [因为您不会有冗余值]

【讨论】:

  • 我编辑了这个例子..所以你可以看到我的意思是什么 INDEX
  • 如果 someList 是一个数组,它们在 INDEX 中不会有冗余值
  • 这取决于数组中有多少元素。如果 array.length == 2,子组件使用相同的 INDEX 获取 props:INDEX 3 次
  • 你不明白
  • 如果这是一个数组,那么索引就不会是多余的,也许每个对象内部的 id attr 可能是多余的
猜你喜欢
  • 1970-01-01
  • 2021-10-08
  • 2015-08-26
  • 2017-09-17
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
相关资源
最近更新 更多