问题
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
回答1:
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://vuejs.org/v2/guide/reactivity.html
回答2:
You can use the object studentData
, it is working well with v-model
.
First, you pass the props like that :
<student-edit-component :student="student">
(no need to use the ${{}}
).
Then in the component `StudentEditComponent', you can use :
props: {
student: {
type: Object,
required: true,
default : () => {},
}
}
You should use the type, required and default properties, it is a good practice. Then
data () {
return {
studentForm: {},
};
},
created() {
this.studentForm = this.student;
}
In the template, you can after that use v-model="studentForm.first_name"
来源:https://stackoverflow.com/questions/63905717/is-there-a-way-to-shorten-defining-v-model-data-vue-js-and-laravel