Remove repeated elements from v-for in VueJS(从 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 中删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 VueJS 中的 v-for 中删除重复的元素


基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01