I have a Vue Component that is a form for creating (or editing) a patient. It contains a lot of information: birthname, firstname, date of birth, birth place, gender, etc.
What are the best practices in terms of maintainability, reactivity and performance to pass those information?
Is this recommended to pass each information item as a prop?
<patient-form
:firstname.sync="patient.firstname"
:lastname.sync="patient.lastname"
:birthdate.sync="patient.birthdate"
... />
Or more recommended to use an object Patient with all the information?
<patient-form :patient="patient" @update="updatePatient"/>
CodePudding user response:
Personally, I prefer the second approach. It looks cleaner. Whenever you want to add a new property like age
you don't have to worry about adding it both in the parent and the child component the object finishes the job. And reactivity wise toRefs can handle it like this.
Or simple snippet
<script setup>
import { toRefs, defineProps } from 'vue'
const props = defineProps({
patient: {
type: Object
}
})
const { patient } = toRefs(props)
But there is also another way in addition to illustrated in the comment section. Let me guess you are fetching the data from server, so you can just pass the id of the patient and fetch inside your child component.
CodePudding user response:
Your requirement is totally depends on the use case of <patient-form>
component and the data you are using in this component.
If you have multiple reference of
<patient-form>
in a parent component.i.e
in case of edit the parent information against each parent record. In this case, I will suggest to get the real time parent information from a database through an API call in the child component itself.Hence, As per my understanding the best approach would be, pass the parent id as a
prop
in the<patient-form>
component and then get the real time updated data by calling an API based on patient id and bind the response in the template. Then on successful edit, you can post the data and emit thesuccess
event to parent.In parent component :
<patient-form :patientid="patient.id" @update="isUpdateSuccess"/>
In child component :
mounted() { // get parent data based on the `patientid` parameter and bind that in the template. } methods: { onUpdate(id) { // post the updated data with the help of an API call. // emit the success event on parent else show the error in the child itself. } }
But if still you already have the
patient
data in your parent component and you want to pass that in the<patient-form>
component, Then your second solution is better than the first one. Go for that.