I have different forms for adding and editing a record and I want to create a reusable component to handle both actions using a single form. When editing a record, I also want my props to be updated. I just want to know if I am applying good practices.
// ------------------------------------------
// Form.vue
// ------------------------------------------
<template>
<div></div>
</template>
<script>
export default {
props: {
contactForm: {
type: Object,
default: () => {
name: "",
gender: "",
address: ""
contact_number: ""
}
}
},
data() {
return {
form: {
name: "",
gender: "",
address: ""
contact_number: ""
}
}
},
methods: {
onSave() {
this.$emit("on-save", this.form);
}
},
watch: {
contactForm: {
immediate: true,
handler(newValue, oldValue) {
this.form = newValue
}
}
}
}
</script>
// ------------------------------------------
// Create.vue
// ------------------------------------------
<Form :contactForm="form" @on-save="onSave"></Form>
<script>
import Form from "./Form";
export default {
components: { Form },
data() {
return {
form: {
name: "",
gender: "",
address: ""
contact_number: ""
}
},
methods: {
onSave() {}
}
}
}
</script>
// ------------------------------------------
// Edit.vue
// ------------------------------------------
<Form :contactForm="form" @on-save="onSave"></Form>
<script>
import Form from "./Form";
export default {
components: { Form },
data() {
return {
form: {
name: "",
gender: "",
address: ""
contact_number: ""
}
},
methods: {
getData() {
axios.get("api/user/1").then(response => this.form = response.data.data);
},
onSave() {}
}
}
}
</script>