将请求后的vuejs数据作为整数数组而不是字符串发送

问题描述 投票:0回答:2

我有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
2个回答
1
投票

您可以使用.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))
  }
}

2
投票

您可以使用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,否则会导致奇怪的行为。

© www.soinside.com 2019 - 2024. All rights reserved.