我遇到了一个问题,Vue将数字类型的输入字段的值转换为字符串,我就是不明白为什么.我遵循的指南没有遇到这个问题,而是按照预期将值作为数字.
vue文档声明,如果输入的类型是数字,vue会将该值转换为数字.
代码源于一个组件,但我将其调整为在JSFiddle:https://jsfiddle.net/d5wLsnvp/3/中运行
<template>
<div class="col-sm-6 col-md-4">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">
{{ stock.name }}
<small>(Price: {{ stock.price }})</small>
</h3>
</div>
<div class="panel-body">
<div class="pull-left">
<input type="number" class="form-control" placeholder="Quantity" v-model="quantity"/>
</div>
<div class="pull-right">
<button class="btn btn-success" @click="buyStock">Buy</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['stock'],
data() {
return {
quantity: 0 // Init with 0 stays a number
};
},
methods: {
buyStock() {
const order = {
stockId: this.stock.id,
stockPrice: this.stock.price,
quantity: this.quantity
};
console.log(order);
this.quantity = 0; // Reset to 0 is a number
}
}
}
</script>
数量价值是个问题.
Object { stockId: 1, stockPrice: 110, quantity: 0 }
但只要我通过使用微调器或键入新值来更改值,控制台就会显示:
Object { stockId: 1, stockPrice: 110, quantity: "1" }
使用Firefox 59.0.2和Chrome 65.0.3325.181进行测试.两者都声明它们是最新的.实际上,我也在微软Edge上试用过,结果也是一样的.
那我还缺什么?为什么Vue不将值转换为数字?