Vue将input \[type = number\]转换为字符串值

JavaScript

Tom阳光达蒙

2020-03-12

我遇到了问题,Vue将类型为number的输入字段的值转换为字符串,而我只是想不通为什么。我遵循的指南没有遇到这个问题,并且按预期方式将值设为数字。

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>

数量是问题。它用0初始化,当我只按“购买”按钮时,控制台显示:

Object { stockId: 1, stockPrice: 110, quantity: 0 }

但是,一旦我通过使用微调器或仅输入新值来更改值,控制台就会显示:

Object { stockId: 1, stockPrice: 110, quantity: "1" }

经过Firefox 59.0.2和Chrome 65.0.3325.181的测试。两者都声明它们是最新的。我实际上也在Microsoft Edge中尝试过,结果相同。

那我在这里想念什么?Vue为什么不将值转换为数字?

第1010篇《Vue将input \[type = number\]转换为字符串值》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
番长GO 2020.03.12

将订单对象更改为:

            const order = {
                stockId: this.stock.id,
                stockPrice: this.stock.price,
                quantity: +this.quantity
            };

这将自动将字符串解析为数字。

通常,来自HTML输入的数据是字符串。输入类型仅检查字段中是否提供了有效的字符串。

斯丁Jim 2020.03.12

您需要使用的.number修饰符v-model,如下所示:

<input v-model.number="quantity" type="number">

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android