在vue.js中更改v-for内部的对象值v-for



我对vue很陌生。我有两个这样的数组数据:

listAccount : [
{
id_acc : a,
amount : 1000
},
{
id_acc : b,
amount : 2000
},
{
id_acc : c,
amount : 1000
}
]
listTransaction : [
{
id_acc : a,
type : inc,
amount : 100
},
{
id_acc : b,
type : inc,
amount : 100
},
{
id_acc : a,
type : dec,
amount : 100
},
{
id_acc : a,
type : dec,
amount : 100
}
]

这是我的组件代码

<div v-for="(list,index) in listAccount" :key="index">
<div> {{list.id_acc}} -- {{list.amount}} </div>
<div> transaction :</div>
<div v-for="(each, index) in listTransaction" :key="index">
<div v-if="each.id_acc == list.id_acc">
<div> {{list.type == inc ? list.amount + each.amount : list.amount - each.amount}} </div>
</div>
</div>
</div>

我得到了这样的结果

my result:
a -- 1000
transaction:
1100
900
900
b -- 2000
transaction:
2100
c -- 1000
transaction:

但是如果事务类型";inc";,交易金额增加了我账户的金额;dec";,如果交易具有相同的idcc,则交易金额将减少我的账户金额。我的预期结果是这样的:

expected result :
a -- 1000
transaction:
1100
1000
900
b -- 2000
transaction:
2100
c -- 1000
transaction:

我不知道如何更改父元素的值。有人能帮我吗?

如注释中所述,使用所需的所有内容制作一个计算道具,然后简单地将其输出到视图中,而不是在视图中动态计算。

与你的预期输出略有不同,但有更多的细节,所以你会有想法。

//
new Vue({
el: '#app',
data: () => ({
listAccount: [{
id_acc: 'a',
amount: 1000
},
{
id_acc: 'b',
amount: 2000
},
{
id_acc: 'c',
amount: 1000
}
],
listTransaction: [{
id_acc: 'a',
type: 'inc',
amount: 100
},
{
id_acc: 'b',
type: 'inc',
amount: 100
},
{
id_acc: 'a',
type: 'dec',
amount: 100
},
{
id_acc: 'a',
type: 'dec',
amount: 100
}
]
}),
computed: {
accountTransactions: function() {
for (let account of this.listAccount) {
account.startingBalance = account.amount
account.transactions = this.listTransaction.filter(i => i.id_acc === account.id_acc)
account.transactions.map(i => {
i.beforeBalance = account.amount
account.amount = i.type === 'inc' ? (account.amount + i.amount) : (account.amount - i.amount)
i.afterBalance = account.amount
})
}
return this.listAccount
}
}
});
.transactions {
margin-bottom: 20px
}
<div id="app">
<div v-for="(account, index) in accountTransactions" :key="index" class="transactions">
<div>
{{ account.id_acc }} -- Starting Balance: {{ account.startingBalance }} End Balance: {{ account.amount }}
</div>
<div> transactions :</div>
<div v-for="(transaction, index) in account.transactions" :key="index">
{{ transaction.beforeBalance }}: {{ transaction.type }} {{ transaction.amount }} = {{ transaction.afterBalance }}
</div>
</div>

<strong>Structure of computed prop</strong>
<pre>{{ accountTransactions }}</pre>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

最新更新