[在特殊情况下,我有一个包含组的列表,我需要在DOM中呈现它,但是我需要它是flat。
const items = [{
group: 'a',
label: ''
},
{
group: 'a',
label: ''
},
{
group: 'b',
label: ''
},
{
group: 'c',
label: ''
}]
常见的解决方案是将其转换为树,例如:
items = [{
group: 'a',
children: []
}]
并使用两个v-for
。但就我而言,我需要将其放平。类似于:
<ul>
<li v-for="item in items">
<span v-if="group">{{ item.label }}</span>
<div v-if="!group">{{ item.label }}</div>
</li>
</ul>
我需要做的第一件事是sortBy
组,但是知道如何前进吗?
您可以使用模板和array.reduce
创建一个分组版本以在模板中使用:
new Vue({
el: "#app",
data() {
return {
items: [{
group: 'a',
label: 'Label a-1'
}, {
group: 'a',
label: 'Label a-2'
}, {
group: 'b',
label: 'Label b-1'
}, {
group: 'c',
label: 'Label c-1'
}]
}
},
computed: {
grouped() {
return this.items.reduce(function(acc, x) {
if (!acc[x.group]) acc[x.group] = [];
acc[x.group].push(x)
return acc;
}, {});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(items, group) in grouped">
<div>{{ group }}:</div>
<div v-for="item in items">
{{ item.label }}
</div>
</div>
</div>