Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

syntaxerron's avatar

Best practices when creating a single Form component for both add and edit

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>
0 likes
2 replies
martinbean's avatar
Level 80

@erron It looks alright. Pass any data to the form as props. I’d just emit a native submit event from the form though. There’s no need to make up your own events:

<!-- resources/js/components/ContactForm.vue -->
<form action="post" v-on:submit.prevent="$emit('submit')">
    <!-- Contact form fields -->
    <button type="submit">Save changes</button>
</form>

If the component is specific a form for adding/editing contacts, then I’d name it as such as well:

<contact-form v-bind:form="form" v-on:submit="updateContact" />
1 like
syntaxerron's avatar

Thank you for your response and recommendation.

1 like

Please or to participate in this conversation.