Here is a practical example, demonstrating how to create an editable address form.
The save button should remain disabled if the form remains unchanged, as there is no need to submit it. However, when a value changes, the save button should become enabled.
In Vue 3, what would be an effective method to achieve this? In a real-world scenario with a large form and numerous input fields listed similarly below, using a watcher for each individual value may not be ideal.
Grouping all the data values into a single form
data object could allow you to utilize a deep watcher, although this approach may lack efficiency.
Another consideration is that when the user initially views the form, the first name is 'john' and the save button is disabled. If the user modifies 'john' to 'johnn', the button should then become enabled. Conversely, reverting the value from 'johnn' back to 'john' should disable the button again as the form returns to its original state.
One potential solution involves establishing an initial value for each form input with v-model, such as:
Vue.createApp({
data() {
first_name: 'john',
initial_first_name: 'john'
}
})
However, implementing this concept efficiently in a substantial form with multiple fields can be challenging, especially if you're unfamiliar with the process.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<script src="https://unpkg.com/vue@3/dist/vue.global.js" defer></script>
<style>
.submit-btn {
color: #fff;
background: #000;
padding: 24px;
}
.submit-btn[disabled] {
color: #fff;
background: #999;
}
</style>
</head>
<body>
<div id="app">
<form @submit="onSubmit" id="test-form">
<label for="first_name">First Name</label>
<input id="first_name"
type="text"
v-model="first_name"
>
<label for="email">Email</label>
<input id="email"
type="email"
v-model="email"
>
<input type="submit"
value="save"
class="submit-btn"
:disabled=""
>
</form>
</div>
<script type="module">
Vue.createApp({
name: 'form_app',
data() {
return {
first_name: 'john',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167c797e7856717b777f7a3875797b">[email protected]</a>'
}
},
methods: {
onSubmit(e) {
e.preventDefault()
console.log('form submitted')
}
}
}).mount('#app')
</script>
</body>
</html>