vue.js - 输入值时获取 NaN
问题描述
我试图从 2 个输入框计算一个值,然后得到这些输入框的总数。然后我试图获取我所有的金额并将它们总计并将它们添加到小计中,但我遇到的问题是,当我在第一个框中输入一个数字时,我的输出NaN
不是 0,我想要它向我展示了一个 0。
这是我的代码
<template>
<div class="content-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Unit</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{ product['name'] }}</td>
<td>
<input type="text" class="form-control" v-model="unit[product['unit']]" @change="calculateCost(product['name'])">
</td>
<td>
<input type="text" class="form-control" v-model="price[product['price']]" @change="calculateCost(product['name'])">
</td>
<td>
{{ cost[product['name']] }}
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
Subtotal: {{ subTotal }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default{
props: [],
data(){
return {
products: [],
unit: {},
price: {},
cost: []
}
},
computed:{
subTotal(){
if(this.cost!== null)
{
if(Object.keys(this.cost).length !== 0){
return Object.keys(this.cost).reduce((carry, item) => {
carry+= Number(this.cost[item])
return carry;
}, Number(0))
}else{
return 0;
}
}
}
},
methods: {
getProducts(){
axios.get(`/api/product/all`).then(response => {
this.products = response.data.products;
});
},
calculateCost(item){
this.cost[item] = Number(this.unit[item]) * Number(this.price[item]);
},
},
mounted() {
this.getProducts();
}
}
</script>
解决方案
问题是v-model
forunit
和price
设置为与给定的键不同的键 to calculateCost()
,这导致查找失败并导致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'])"> ✅
将键设置为product['name']
确保正确查找unit
和price
in calculateCost()
。由于用户可以输入无效值(非数字字符串)或省略值,因此可以得到 get NaN
,因此添加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;
},
此外,您可能希望成本对用户输入做出反应,因此请切换@change
到@input
:
<input v-model="unit[product['name']]" @input="calculateCost(product['name'])">
<input v-model="price[product['name']]" @input="calculateCost(product['name'])">
推荐阅读
- python - 使用引导主题创建注册过程
- javascript - 当属性名称在 JavaScript 中是可变的时获取对象的属性
- r - 在 r 中使用 magick 包时出错,内存分配错误
- python - 将 3D 曲面(由 plot_trisurf 生成)投影到 xy 平面并在 2D 中绘制轮廓
- windows - 访问 nginx 后面的 Windows Admin Center
- sql - SQL 中的 LEFT JOIN 但排除连接 where table1.column1 = 'specific_value'
- javascript - rectMode(CENTER)不围绕其中心旋转形状
- php - PHP While 循环使服务器超时
- html - 如何使用目录的绝对路径从 angular 8 在新选项卡中打开目录?
- javascript - 在 .map() 方法中检查匹配的字符串