我对 vue 还很陌生。 我有 2 个这样的数组数据:
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”,则如果交易具有相同的 id_acc,则交易金额会减少我的帐户金额。我的预期结果是这样的:
expected result :
a -- 1000
transaction:
1100
1000
900
b -- 2000
transaction:
2100
c -- 1000
transaction:
我不知道如何更改父元素值。有人可以帮助我吗?
最佳答案
正如评论中提到的,使用您需要的所有内容创建一个计算 Prop ,然后将其简单地输出到 View 中,而不是在 View 内动态计算内容。
与您的预期输出略有不同,但有更多细节,以便您了解想法。
//
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>
关于vue.js - 更改 vue.js 中 v-for 内的对象值 v-for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63886697/