在 VueJS 中从 v-for 中删除重复元素 [英] Remove repeated elements from v-for in VueJS

查看:127
本文介绍了在 VueJS 中从 v-for 中删除重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the following code to display categories from an array. The array may contain duplicate categories. Is there any way I can only select unique elements in 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' }
    ]

推荐答案

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

You can create a computed property with the unique values you want. If you include Lodash in your project, try _.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))]
}

注意:我已经转换了 设置为数组,因为Vue.js 似乎无法迭代Set(或任何其他Iterator).

Note: I've converted the Set to an array as Vue.js doesn't seem able to iterate the Set (or any other Iterator).

这篇关于在 VueJS 中从 v-for 中删除重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆