0👍
Almost all type of inputs return a string. You can use
<input type="number" class="form-control" v-model="unit[product['unit']]" @change="calculateCost(product['name'])">
or
<input type="text" class="form-control" v-model.number="unit[product['unit']]" @change="calculateCost(product['name'])">
- [Vuejs]-BootstrapVue's b-nav with lazy loading
- [Vuejs]-How to prevent props from reseting when child component updates?
0👍
The problem is the v-model
for unit
and price
are set to the different keys than the one given to calculateCost()
, which causes the lookups to fail and results in NaN
:
<input v-model="unit[product['unit']]" @change="calculateCost(product['name'])"> ❌
^^^^^^ ^^^^^^
<input v-model="price[product['price']]" @change="calculateCost(product['name'])"> ❌
^^^^^^^ ^^^^^^
<input v-model="unit[product['name']]" @change="calculateCost(product['name'])"> ✅
<input v-model="price[product['name']]" @change="calculateCost(product['name'])"> ✅
Setting the keys to product['name']
ensures the correct lookup for unit
and price
in calculateCost()
. Since the user could enter invalid values (non-numeric strings) or omit a value, it’s possible to get NaN
, so it would be a good idea to add a NaN
-check in calculateCost()
:
calculateCost(item) {
const unit = Number(this.unit[item]);
const price = Number(this.price[item]);
if (Number.isNaN(unit) || Number.isNaN(price)) return;
this.cost[item] = unit * price;
},
Also, you probably want the cost to react to user input, so switch from @change
to @input
:
<input v-model="unit[product['name']]" @input="calculateCost(product['name'])">
<input v-model="price[product['name']]" @input="calculateCost(product['name'])">
- [Vuejs]-I want to use jest to write vue-next ,but I meet some matters
- [Vuejs]-Vue.js: unwanted effect every time the view is rendered
Source:stackexchange.com