【问题标题】:How can i post Array Data with Vue axios from Data obtained from an API如何从 API 获得的数据中使用 Vue axios 发布数组数据
【发布时间】:2020-07-20 17:33:00
【问题描述】:

我遇到了一个问题,我有一个表单,其中的输入是根据 API 返回的结果动态生成的。我用axios可以成功获取数据,但问题是当我想将用户输入的数据数组post回api时,我不能。

模板如下所示:

<form @submit.prevent="getReference" class="form-material form-horizontal">
  <div class="row">
    <div class="col-md-6"
      v-for="(item, index) in items"
      :key="item.id">
      <div class="card bg-light-inverse ribbon-wrapper">
        <div class="card-block">
          <div class="ribbon ribbon-danger">{{index + 1}}</div>
          <div class="row ribbon-content">

            <input v-model="item.id" />
            <label class="col-md-12 text-themecolor">Enter Amount To Pay</label>
            <div class="card col-md-12 m-t-10">
              <input
                v-model.number="item.amount"
                type="number"
                class="form-control"
                placeholder
                max
                min
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <button
    class="btn btn-rounded btn-outline-danger waves-effect waves-dark"
  >Get Refrence</button>
</form>

而JS代码是:

export default {
  data() {
    return {
      items: {},
      item: []
    };
  },
  created() {
    let uri = `/Api/${this.$route.params.id}/items`;
    this.axios.get(uri).then(response => {
      this.items = response.data;
    });
  },
  // could go with computed method to check if there is data but well :
  methods: {
    getReference() {
      console.log(this.item);
      let uri = "/api/reference";
      this.axios.post(uri, this.item).then(response => {
        this.$router.push({ name: "fee" });
      });
    },
  }
};

当我尝试发布表单时,没有发送任何内容,并且在控制台 uncaught exception: Object 内引发错误。我似乎无法弄清楚这里出了什么问题。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript laravel vue.js axios single-page-application


    【解决方案1】:

    您在模板部分将items 循环为item,并使用item 绑定输入。发送时,您在 axios 中使用 this.item

    输入数据绑定到items 本身,因为您正在循环它。您可以尝试在 axios 部分发送items 而不是item

      methods: {
        getReference() {
          console.log(this.item);
          let uri = "/api/reference";
          this.axios.post(uri, this.items).then(response => {
            this.$router.push({ name: "fee" });
          });
        },
      }
    

    您可以删除数据部分中的item,因为在输入部分中使用相同的项目绑定值时会导致问题。

    【讨论】:

    • 你好@Rijosh,当我改为发布项目时,上一次调用的整个对象被发送回服务器,并且在所述请求中没有看到用户输入的数据。
    • 谢谢,我能够按照您的建议找到对我有用的问题。
    猜你喜欢
    • 2020-05-18
    • 2021-09-22
    • 2023-03-15
    • 2020-09-27
    • 2021-03-07
    • 2021-07-22
    • 2021-10-20
    • 2019-01-26
    • 2020-02-27
    相关资源
    最近更新 更多