我遇到了一个问题,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不将值转换为数字?

推荐答案

您需要使用.number modifier for v-model,如下所示:

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

注意:空字符串('')不能转换为数字,因此可能需要单独处理.

Vue.js相关问答推荐

在 Nuxt3 中使用 Vue3 vue-ganntastic 插件

Vue CLI: 如何在一个vtextfield更改时让另一个vtextfield的值也同时更改,但同时又可以覆盖它?

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

如何在 Vue 中编译从外部 api 加载的模板

Vue watch 意外调用了两次

为什么Vue.js 使用单字标签

Vuetify 容器不会填充高度

Vue.js + Vuex:如何改变嵌套项状态?

Vuex - 如何跨不同选项卡持久存储更新?

错误:vue-loader 要求 @vue/compiler-sfc 存在于依赖树中

vue-test-utils:无法覆盖属性 $route,这通常是由于插件将该属性添加为只读值

如何告诉 Vue-cli 我的应用程序的入口点在哪里?

如何使用 JavaScript 按索引删除数组元素?

根据路由动态插入 CSS 类到导航栏

Leaflet+Vue+Vuetify / Leaflet map 隐藏 vuetify 弹出对话框

在路由更改之前显示确认对话框

了解 Nuxt.js 中的State状态和Getters:Getters不起作用

$set 不是函数

为什么 router.currentRoute.path 没有react?

如何在 vuejs 中的基于类的组件中编写计算设置器