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

问题描述

我的想法很新。 我有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 : 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:

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

解决方法

如评论中所述,使用所需的全部内容制作一个计算道具,然后将其简单地输出到视图中,而不是在视图中即时计算事物。

与您的预期输出略有不同,但提供了更多详细信息,因此您可以理解。

//
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: '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>