【问题标题】:Create JSON object from vuejs form data从 vuejs 表单数据创建 JSON 对象
【发布时间】:2021-03-08 01:32:01
【问题描述】:

我正在尝试从提交时的表单数据创建一个 JSON 对象。

我已经设法让它与一个变量一起工作。有没有更好的方法来创建 JSON 对象?

表格

<form @submit.prevent="submit">
   <div class="form-group">
      <label class="inputa-label" for="exampleInputEmail1"
         >Email address</label
         >
      <input
         type="email"
         class="form-control inputa"
         id="exampleInputEmail1"
         placeholder="Enter email"
         required
         v-model="email"
         />
   </div>
   <div class="form-group">
      <label class="inputa-label" for="exampleInputPassword1"
         >Phone number</label
         >
      <input
         type="number"
         class="form-control inputa"
         id="exampleInputPassword1"
         placeholder="Phone"
         v-model="phone"
         />
   </div>
   <div class="form-group">
      <label class="inputa-label" for="exampleInputPassword1"
         >Information</label
         >
      <textarea
         class="form-control inputa"
         aria-label="With textarea"
         v-model="information"
         ></textarea>
   </div>
   <button
      type="submit"
      style="font-weight:600; padding: .8125rem 1.25rem"
      class="btn btn-primary"
      >
   Submit
   </button>
</form>

方法:

  data() {
    return {
      email:"",
      phone:"",
      information:"",
    };
  },
  methods: {
    submit() {

      var data = '{ "Email":"' + this.email + '" , "Phone":"' + this.phone + '", "Information":"' + this.information + '" }';
      
    },
  },

我已经让它与一个变量一起工作,但我想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • 提醒一下,默认提交功能会为您发送表单数据,您不需要自己生成 JSON 有效负载。但是,如果您仍然希望发送一些自定义有效负载,如果您使用的是 Axios,您可以只在 axios.post 请求中提供一个 javascript 对象!
  • 我正在使用 axios 发布变量“数据”。我只是想知道是否有更熟练的方法来做到这一点,而不是我如何处理我的变量。谢谢@Ayudh
  • 你可以从json对象制作,然后使用JSON.stringify

标签: javascript arrays json vue.js


【解决方案1】:

回答这个问题,我想你要找的是JSON.stringify()

const data = JSON.stringify({
  Email: this.email,
  Phone: this.phone,
  Information: this.information
})

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2020-05-28
    • 1970-01-01
    • 2014-01-05
    • 2013-05-25
    • 2019-07-27
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多