如何确定模板内没有任何重复的Vue?
我的情况是,数据是对象和键的数组,其中包含一个对象的值,其中包含多个对象。因此,这将是vue模板语法中的嵌套v-for。
{
"matches": [
{
"birthday": "1/29/2019",
"household": {
"0": {
"relationship": "brother"
},
"1": {
"relationship": "brother"
}
}
}
]
}
我只想显示每个家庭1个唯一的关系。请参阅小提琴以进行进一步检查https://jsfiddle.net/sxmhv3t7/
答案 0 :(得分:0)
您可以使用computed
属性来使matches
数组唯一。
例如:
computed: {
uniqueMatches () {
return this.matches.map(item => {
let households = Object.values(item.household)
let relationships = households.map(item => item.relationship)
const uniqueRelationships = [...new Set(relationships)]
item.household = uniqueRelationships.reduce((acc, cur, idx) => {
acc[idx] = {}
acc[idx].relationship = cur
return acc
}, {})
console.log(item)
return item
})
}
}
,然后在模板中使用uniqueMatches
代替matches
jsfiddle中的演示
答案 1 :(得分:0)
您可以对数据进行一些处理,并在uniqueHouseholdMembers
数组中的每个匹配项上创建一个matches
数组属性,然后仅打印出这些值:
matches.forEach(match => {
let houseHolds = Object.values(match.household);
match.uniqueHouseholdMembers = houseHolds.reduce((acc, household) => {
// check if household member has already been added to our growing list
let isUniqueRelationship = !acc.includes(household.relationship);
// add household member if unique
if (isUniqueRelationship) {
acc.push(household.relationship);
}
return acc;
}, []);
});
// output using the data you provided:
// match[0].uniqueHouseholdMembers -> ['brother']
// match[1].uniqueHouseholdMembers -> ['sister']
// and if you have a 3rd match entry with more household members:
// match[2].uniqueHouseholdMembers -> ['brother', 'father', 'stranger']