Skip to content
Advertisement

Is there a way to shorten defining v-model data, Vue.js and Laravel

On my edit page of CRUD project, I have a code that fills the form with values of which record is being edited.
I use v-model to define HTML inputs, but the code seems too long.
I get the data from the prop, and fill the v-model.

My code that fills v-model

created() {
            this.studentData = this.student;
            this.first_name = this.student.first_name;
            this.last_name = this.student.last_name;
            this.student_number = this.student.last_name;
            this.phone_number = this.student.phone_number;
            this.email = this.student.email;
            this.birth_date = moment(this.student.birth_date).format('YYYY-MM-DD');
            this.school_name = this.student.school_name;
        }

The way I get the data using prop: props: ['student'] and in blade <student-edit-component :student="{{$student}}">

Defining v-models in script

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

That fills the value on the form inputs with it’s data.

Is there a way to shorten this code using props or arrays?

Please help me, I’m so new to Vue

Advertisement

Answer

You can change your model of data adding a new layer. For example:

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

Then in created you can use simple

  created() {
    this.currentStudent = this.student;
    this.currentStudent.birth_date = moment(this.student.birth_date).format('YYYY-MM-DD');
  },

And in all component replace names by names with currentStudne eg in v-models:

first_name -> currentStudne.first_name

You can also read about Vue.$set

https://v2.vuejs.org/v2/guide/reactivity.html

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement