Handling user input in Vue.js forms involves using the v-model directive, which creates a two-way binding between the form input and a data property in your Vue instance. Here's a step-by-step guide on how to handle user input in Vue.js forms:
Create a Vue Instance:
Start by creating a Vue instance. You can do this using the new Vue()
constructor.
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Form Example</title>
</head>
<body>
<div id="app">
<!-- Your form will go here -->
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="your-script.js"></script>
</body>
</html>
Create Data Properties: Define data properties in your Vue instance to store the form input values.
javascriptnew Vue({
el: '#app',
data: {
formData: {
username: '',
email: '',
// Add other form fields as needed
}
}
});
Create the Form:
Build your form in the template using the v-model
directive to bind form inputs to the corresponding data properties.
html<div id="app">
<form>
<label for="username">Username:</label>
<input type="text" id="username" v-model="formData.username">
<label for="email">Email:</label>
<input type="email" id="email" v-model="formData.email">
<!-- Add other form fields as needed -->
<button type="submit">Submit</button>
</form>
<!-- Display form data for testing -->
<div>
<h2>Form Data:</h2>
<pre>{{ formData }}</pre>
</div>
</div>
Handle Form Submission (Optional):
If you want to perform an action when the form is submitted, you can use the @submit
event.
html<form @submit.prevent="handleSubmit">
<!-- Form fields -->
<button type="submit">Submit</button>
</form>
And in your Vue instance:
javascriptnew Vue({
el: '#app',
data: {
formData: {
username: '',
email: '',
// Add other form fields as needed
}
},
methods: {
handleSubmit() {
// Handle form submission logic here
console.log('Form submitted!', this.formData);
}
}
});
The @submit.prevent
prevents the default form submission and allows you to handle it manually using the handleSubmit
method.
That's it! With these steps, you've set up a basic form in Vue.js with two-way data binding using the v-model
directive.