Working on a Vue application, I have various form components that can either create a new record or edit an existing one. When a form is active, clicking on another record or the create button should replace or clear the form's contents.
The issue arises from the repetition in setting up data properties and watch functions within my code.
For instance:
props: ["record"],
data() {
return {
name: this.record ? this.record.name : "",
age: this.record ? this.record.age : null
};
},
watch: {
record(record) {
this.name = record ? record.name : "";
this.age = record ? record.age : null;
}
}
I find it cumbersome to repeat the setup process in both the data function and the watch function for every property in the record object. This approach becomes error-prone as the number of properties grows.
Is there a way to consolidate this initialization logic into a single location and eliminate the redundancy?