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 中删除重复的元素


- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01