Remove repeated elements from v-for in VueJS

两盒软妹~` 提交于 2019-11-28 09:48:04

问题


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>

Array:

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' }
    ]

回答1:


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))
  }
}

and in your template

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

If you're not keen on introducing Lodash (or other utility libraries), the same can be achieved with a Set

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

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




回答2:


You can create a computed property: uniqProducts which will return unique array for your products, you will need to make following changes:

HTML

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

in vue instance you have to write a computed property which can use any technique (many listed here) to get uniq array.

_ here can be lodash or underscore.

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


来源:https://stackoverflow.com/questions/41735043/remove-repeated-elements-from-v-for-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!