我有一個像這樣創建的串列:
<tbody>
<tr v-for="(post, index) in posts" v-bind:index="index">
<td>{{ post.rut }}</td>
<td>{{ post.names }} {{ post.father_lastname }} {{ post.mother_lastname }}</td>
<td>
<input type="text" @blur="handleBlur(post.amount)" id="exampleInputEmail1" v-model="post.amount" placeholder="Ingresa el monto">
</td>
</tr>
</tbody>
我在 Vuejs 中有一個這樣的方法:
handleBlur(value) {
this.total_inputs = parseInt(this.total_inputs) parseInt(value);
},
問題是,如果我編輯任何輸入,它會正確添加,我的意思是:
如果它是 0.. 并且我在輸入中添加一個值 3 它會說 3 0 = 3 等等...
問題是我不需要添加,因為如果我編輯相同的輸入,它有 3 并且我更改為 4 它應該說總數 = 4 但它說 3 4 = 7 這是錯誤的,因為 4 取代了 3 數字所以我想知道如何修復我的代碼來做到這一點?
謝謝
uj5u.com熱心網友回復:
您遇到此問題handleBlur是因為每次任何欄位模糊時都會被呼叫。這意味著當您模糊同一欄位時,您仍在添加數字,盡管此數字不再存在。
在您的代碼中:
<input type="text" @blur="handleBlur(post.amount)" id="exampleInputEmail1" v-model="post.amount" placeholder="Ingresa el monto">
您已經定義了模型 ( v-model="post.amount"),這意味著post當您修改欄位時,Vue 會在物件中自動更改它。
這也意味著您不必傳遞post.amount給 blur 函式,而只需呼叫handleBlur:
<input type="text" @blur="handleBlur" id="exampleInputEmail1" v-model="post.amount" placeholder="Ingresa el monto">
然后在您的handleBlur方法中,您可以簡單地遍歷post陣列并總結不同的post.amount值:
handleBlur() {
let totalAmount = 0;
for (let i = 0, len = this.posts.length; i < len; i ) {
const post = this.posts;
totalAmount = post.amount;
}
this.total_inputs = totalAmount;
}
一種更簡短的寫法是簡單地Array.reduce()像這樣使用:
handleBlur() {
this.total_inputs = this.posts.reduce((totalAmount, post) => totalAmount post.amount, 0);
}
這兩段代碼都在做完全相同的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/381427.html
標籤:Vue.js
