deeej
deeej

Reputation: 387

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.

Upvotes: 2

Views: 11143

Answers (1)

Arnesfield
Arnesfield

Reputation: 508

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

Upvotes: 7

Related Questions