【问题标题】:Number saved as String in Firestore javascript在 Firestore javascript 中保存为字符串的数字
【发布时间】:2020-11-15 19:50:04
【问题描述】:

我正在使用 Vue 框架

这是 HTML 代码

<input  name="quantity" type="number" v-model="product.price" placeholder="price" >

脚本

product: {
        name:String,
        price: null,
      },
addProduct() {
      this.$firestore.Products.add(this.product);
    },

firestore document

我想将价格保存为数字。

【问题讨论】:

    标签: javascript vue.js google-cloud-firestore


    【解决方案1】:

    使用v-model.number modifier

    <input  name="quantity" type="number" v-model.number="product.price" placeholder="price" >
    

    【讨论】:

      【解决方案2】:

      当您在 HTML 中的文本输入字段中输入数据时,它的值在 JS 代码中变为字符串。您需要将实际值显式转换为数字。即使您设置了输入 type="number",它也只决定了键盘移动用户在输入值时看到的内容。如果通过JS访问它仍然是一个字符串

      一种方法:

      const price = Number(price);
      

      Documentation for Number

      另一种方法是解析它

      parseFloat(price)
      

      编辑:@Beyers 的方法似乎是 Vue 的最佳实现。

      【讨论】:

        【解决方案3】:

        当您在 javascript 中捕获表单值时,默认情况下它是字符串。即使您在表单文本字段中输入数字。

        product: {
            name:String,
            price: null,
        },
        
        .......
        
        addProduct() {
            data_firestore = {...this.product};
            data_firestore.price = parseFloat(data_firestore.price)
            this.$firestore.Products.add(data_firestore);
        },
        

        我正在使用扩展运算符,因为我不知道您是否使用 product 对象的 watch 方法。所以复制然后修改对我来说似乎更安全。您也可以对实际对象进行 parseFloat() 的直接转换。

        【讨论】:

          猜你喜欢
          • 2018-07-25
          • 1970-01-01
          • 2023-03-03
          • 2022-11-25
          • 1970-01-01
          • 1970-01-01
          • 2019-03-31
          • 1970-01-01
          • 2023-02-07
          相关资源
          最近更新 更多