从VueJS中的v-for中删除重复的元素

Gij*_*ese 2 vue.js vue-component vuejs2

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

<li v-for="product in products">
{{product.category}}
</li>
Run Code Online (Sandbox Code Playgroud)

阵:

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' }
    ]
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 11

只需使用您想要的唯一值创建计算值.如果您在项目中包含Lodash,只需使用

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

computed: {
  productCategories () {
    return uniq(this.products.map(({ category }) => category))
  }
}
Run Code Online (Sandbox Code Playgroud)

并在您的模板中

<li v-for="category in productCategories">
  {{category}}
</li>
Run Code Online (Sandbox Code Playgroud)

如果你不热衷于引入Lodash(或下划线),可以用a来实现 _.uniq

productCategories () {
  return [...new Set(this.products.map(({ category }) => category))]
}
Run Code Online (Sandbox Code Playgroud)

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