gpt4 book ai didi

javascript - Vue js 带条件的 for 循环

转载 作者:行者123 更新时间:2023-12-02 21:17:28 27 4
gpt4 key购买 nike

我有一个看起来像这样的对象:

分组联系人:

{
4: [
{name: 'foo'},
{name: 'bar'}
],
6: [
{name: 'foo bar'},
]
}

然后我有另一个数组:

companyList.models:

models: [
{id:4, name: 'company A'},
{id:6, name: 'company B'},
]

因此,我公司中的 ID 类似于 groupedContacts 中的键,在一个数组中我有公司名称,在另一个数组中我有公司的联系人。

现在我想在多个表中显示它们,当然就像这样

Table 1
Company A (id4)
- foo
- bar

Table2
Company B (id6)
- foo bar

这是我的代码,不幸的是我得到了 2 个公司的 2 个表格,但没有联系人。我没有收到任何错误:

<div
v-for="(company, key) in companyList.models"
:key="key"
class="table table--hover mt-4"
>
<h4 class="mb-4" v-html="company.name" />
<table>
<thead>
<tr>
<th class="text-left" v-html="__t('name')" />
</tr>
</thead>
<tbody
v-for="(groupContacts, key) in groupedContacts"
:key="key"
v-if="company.id === key"
>
<tr
v-for="(contact, contactKey) in groupContacts"
:key="contactKey"
>
<td v-html="contact.name" />
</tr>
</tbody>
</table>
</div>

这是我在浏览器中的结果:

enter image description here

最佳答案

我建议使用名为 companies 的计算属性,如下所示:

 computed: {
companies() {

return this.models.map(c => {
c.groups = this.groupContacts[c.id];
return c;
})
}

}

然后像这样循环:

 <div v-for="(company, key) in companies" :key="key" class="table table--hover mt-4">
<h4 class="mb-4">{{company.name}}</h4>

<table>
<thead>
<tr>
<th class="text-left">Name</th>

</tr>
</thead>
<tbody>
<tr v-for="(contact, contactKey) in company.groups" :key="contactKey">
<td> {{contact.name}}</td>
</tr>
</tbody>
</table>
</div>

new Vue({
el: '#app',

data() {

return {
groupContacts:

{
4: [{
name: 'foo'
},
{
name: 'bar'
}
],
6: [{
name: 'foo bar'
}, ]
},
models: [{
id: 4,
name: 'company A'
},
{
id: 6,
name: 'company B'
},
]
}
},
computed: {
companies() {

return this.models.map(c => {
c.groups = this.groupContacts[c.id];
return c;
})
}

}
})
<body>
<div id="app">

<div v-for="(company, key) in companies" :key="key" class="table table--hover mt-4">
<h4 class="mb-4">{{company.name}}</h4>

<table>
<thead>
<tr>
<th class="text-left">Name</th>

</tr>
</thead>
<tbody>
<tr v-for="(contact, contactKey) in company.groups" :key="contactKey">
<td> {{contact.name}}</td>
</tr>
</tbody>
</table>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>

关于javascript - Vue js 带条件的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60931230/

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