【问题标题】:sending vuejs data post request as array of ints instead of strings将 vuejs 数据发布请求作为整数数组而不是字符串发送
【发布时间】:2017-12-21 00:27:41
【问题描述】:

我有 weightsvalues 的 2 个输入框,然后我可以单击一个按钮自动创建更多。这部分工作正常。

现在的问题是服务器需要一个包含整数数组而不是字符串的 JSON formdata 请求。

postdata 应该是这样的:

{"stuff": {"weights": [2, 5, 3], "values": [654, 23, 3]}}

这就是它最终的样子:

{"stuff": {"weights": ["2", "5", "3"], "values": ["654", "23", "3"]}}

我已经尝试搜索如何将数据数组类型设置为int,如何将v-model保存为int等。

我相信这是所有相关代码:

<template>
..

<div v-for="(weight, index) in weights">
  <div>
    <label for="w">weight:</label>
    <input v-model="weights[index]">
    <label for="v">value:</label>
    <input v-model="values[index]">
  </div>
</div>

..
</template>

<script>
export default {
  data () {
    return {
      weights: [],
      values: []
    }
  },
  methods: {
    solve: function () {
      var formData = {
        stuff: {
          weights: this.weights,
          values: this.values
        }
      }
      axios.post('http://localhost:8000/my/api/url', formData).then(response => {
        console.log(response)
      }).catch(e => {
        console.log(e)
      })
    },
  ...
</script>

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    您可以使用 parseInt 来转换它们:

    export default {
      data () {
        return {
          weights: [],
          values: []
        }
      },
      computed: {
        formData() {
            return {
                stuff: {
                    weights: this.weights.map((x) => parseInt(x, 10),
                    values: this.values.map((x) => parseInt(x, 10)
                }
            }
        }
      },
      methods: {
        solve: function () {
          axios.post('http://localhost:8000/my/api/url', this.formData).then(response => {
            console.log(response)
          }).catch(e => {
            console.log(e)
          })
        },
      ...
    

    我使用了一个计算变量来使 API 调用代码更简洁,但它在那里的工作方式相同。额外的参数10 对 parseInt 很重要,它确保整数以 10 为底,否则会导致奇怪的行为。

    【讨论】:

    • 非常感谢
    【解决方案2】:

    您可以使用.number 修饰符:

    <input v-model.number="weights[index]">
    

    但这允许非整数数字和字符串(例如,如果输入为空,它可以是空字符串)。因此,您应该在 API 调用中将权重显式转换为整数:

    // You should validate the data first
    
    var formData = {
      stuff: {
        weights: this.weights.map(x => parseInt(x, 10)),  // Convert to integer
        values: this.values.map(x => parseInt(x, 10))
      }
    }
    

    【讨论】:

    • 哇,非常感谢!已经为此苦苦挣扎了好几个小时。我确实在 GitHub 上看到有人提到你必须输入数字,但我愚蠢地将其添加为 &lt;input v-model="weights[index]" number&gt;.. doh!在我的情况下,所有输入字段都是必需的,所以我认为 v-model.number 解决方案是完美的
    • 好答案,我错过了它们是数组。我建议parseInt 的第二个参数包含 10 的基数。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    • 嗯,我没有意识到 radix 参数可能会在实现中出现问题。已更新。
    • 我只见过一次它在实践中引起了问题,但那一天太可怕了哈哈。它发生在字符串有前导 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2022-08-15
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    相关资源
    最近更新 更多