【问题标题】:Remove repeated elements from v-for in VueJS从 VueJS 中的 v-for 中删除重复的元素
【发布时间】:2017-06-03 18:05:27
【问题描述】:

我正在使用以下代码来显示数组中的类别。该数组可能包含重复的类别。有什么办法我只能在 VueJS 中选择独特的元素?

<li v-for="product in products">
{{product.category}}
</li>

数组:

products: [
      { id: '1', title: 'Test 1', category: 'Test 3' },
      { id: '2', title: 'Test 2', category: 'Test 1' },
      { id: '3', title: 'Test 3', category: 'Test 2' },
      { id: '3', title: 'Test 4', category: 'Test 1' },
      { id: '5', title: 'Test 5', category: 'Test 3' }
    ]

【问题讨论】:

  • 这是一个数组,所以过滤它的重复值。也许使用_.uniqBy
  • 对不起,我是 VueJS 的新手。听说vuejs2没有过滤选项

标签: vue-component vuejs2 vue.js


【解决方案1】:

您可以创建一个计算属性:uniqProducts,它将为您的products 返回唯一数组,您需要进行以下更改:

HTML

<li v-for="product in uniqProducts">
  {{product.category}}
</li>

vue 实例中,您必须编写一个 computed property,它可以使用任何技术(许多列出的 here)来获取 uniq 数组。

_ 这里可以是lodashunderscore

computed: {
   uniqProducts () {
      return _.uniqBy(this.products, 'property')
   }
}

【讨论】:

  • 但这如何使用“独特”的产品?依据是什么?
  • @GijoVarghese 我已经开始在 HTML 中使用uniqProducts,它将从计算属性中获取唯一数组,您可以传递您想要唯一性的属性。
  • 我可以轻松地从后端创建独特的分离。我想知道是否有可能在 vuejs 中从 JSON 之类的复杂数组中选择唯一的。我将使用数组更新问题
【解决方案2】:

您可以使用所需的唯一值创建计算属性。如果您在项目中包含 Lodash,请尝试 _.uniq

import uniq from 'lodash/uniq'
// ...snip

computed: {
  productCategories () {
    return uniq(this.products.map(({ category }) => category))
  }
}

在你的模板中

<li v-for="category in productCategories">
  {{category}}
</li>

如果您不热衷于引入 Lodash(或其他实用程序库),也可以通过 Set 实现相同的目的

productCategories () {
  return [...new Set(this.products.map(({ category }) => category))]
}

注意:我已经 converted the Set to an array,因为 Vue.js 似乎无法迭代 Set(或任何其他 Iterator)。

【讨论】:

  • 好的。非常感谢。但是之前的“……”是什么?这是javascript语法还是vuejs?
  • @Gijo 是 JavaScript spread 运算符。您也可以使用Array.from(见链接帖子)
  • @phil 如何获取和输出产品的其他属性?我做了一个 Codepen 来演示这个问题codepen.io/jmar/pen/eEYGXW
  • @jmartsch 我建议你打开一个新问题
猜你喜欢
  • 1970-01-01
  • 2020-08-19
  • 2021-12-21
  • 2020-04-22
  • 2020-10-10
  • 2021-10-12
  • 2019-12-19
  • 2019-06-18
  • 2016-05-29
相关资源
最近更新 更多