gpt4 book ai didi

javascript - 如何根据 v-for 循环中的数据属性对元素进行分组?

转载 作者:行者123 更新时间:2023-12-03 00:49:02 26 4
gpt4 key购买 nike

我想根据 v-for 循环中的“group”属性对元素进行分组。该数据是从 API 获取的。我该如何解决这个问题?

这就是我想要的:

enter image description here

这是我的代码:https://jsfiddle.net/dowhiledo/d7gfr1oy/5/

var example1 = new Vue({
el: '#example',
data: {
people: [ // ordered by group
{ name: 'Mary', group: 1 },
{ name: 'John', group: 1 },
{ name: 'Peter', group: 1 },
{ name: 'Freddie', group: 2 },
{ name: 'Paul', group: 2 },
{ name: 'Alfred', group: 5 },
{ name: 'George', group: 5 }
]
}
});
li {
border: 1px solid blue
}

.group {
border: 4px solid red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>



<div id="example">
<ul>
<li v-for="p in people">
{{ p.group }} - {{ p.name }}
</li>
</ul>
</div>

最佳答案

为了得到这个结果,你必须将你的数组除以,然后你可以根据你想要的这些组在html中创建一个循环。

尝试使用以下代码来获取结果:

HTML

<div id="example">
<template v-for="group in peopleGroup">
<ul>
<li v-for=" people in group">
{{ people.group }} - {{ people.name }}
</li>
</ul>
</template>
</div>

VueJS - 脚本

var example1 = new Vue({
el: '#example',
data: {
people: [ // ordered by group
{ name: 'Mary', group: 1 },
{ name: 'John', group: 1 },
{ name: 'Peter', group: 1 },
{ name: 'Freddie', group: 2 },
{ name: 'Paul', group: 2 },
{ name: 'Alfred', group: 5 },
{ name: 'George', group: 5 }
],
peopleGroup: {}
},
mounted(){
this.peopleGroup = this.parsePeopleGroup( this.people );
},
methods: {
parsePeopleGroup( arrayPeople ) {
let newArray = {};
arrayPeople.map( people => {
if( !newArray[ people.group ] )
newArray[people.group] = []

newArray[people.group].push( people );
})
return newArray;
}
}
});

这里的代码:http://jsfiddle.net/qb9dmhy2/20/

关于javascript - 如何根据 v-for 循环中的数据属性对元素进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53134322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com