我使用以下代码来显示数组中的类别。该数组可能包含重复的类别。有什么方法可以让我在 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' }
]
您可以使用所需的唯一值创建计算属性。如果您的项目中包含 Lodash,请尝试_.uniq https://lodash.com/docs/4.17.15#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 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set
productCategories () {
return [...new Set(this.products.map(({ category }) => category))]
}
Note: I've 转换了Set到一个数组 https://stackoverflow.com/questions/20069828/how-to-convert-set-to-array因为 Vue.js 似乎无法迭代Set
(或任何其他Iterator
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)