Skip to content Skip to sidebar Skip to footer

Putting Data Inside Prop To Make It Look Tidy Vue.js

I have a create page, I make a POST request using Axios and it works great. But I think my code is not healthy at all. That is how I define my props: data () { return {

Solution 1:

While the previous answer is correct for this particular use-case, if you were to add properties that you don't want to send, it wouldn't work anymore. A better approach is to put all those properties inside an object, let's name it studentData, like this:

data() {
  return {
    studentData: {
      first_name: '',
      last_name: '',
      student_number: '',
      phone_number: '',
      email: '',
      birth_date: '',
      school_name: '',
    },
  };
}

and then you can do

axios.post('/api/students', this.studentData);

Note that you'll also need to update your v-models like v-model="studentData.first_name" instead of v-model="first_name".

Solution 2:

You can access component props or data from this.$props or this.$data,

So you can simply do

axios.post(`/api/students`, this.$data);

But this means that your are sending the entire component data on the request, to avoid this, try @BogdanL answer which is recommended.

Post a Comment for "Putting Data Inside Prop To Make It Look Tidy Vue.js"