简体   繁体   中英

Create JSON object from vuejs form data

I'm trying to create a JSON object from form data on submit.

I've managed to get it working with a variable. Is there a better way to create a JSON object?

Form

<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>

Method:

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

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

I've got it working with a variable, but I want to know if there is a better way to do this.

Answering the question, I think what you're looking for is JSON.stringify() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM