In Vue.js 3, working with form elements involves using the v-model
directive and handling user input events to update the underlying data. Vue.js provides two main ways to handle form input:
Two-way Data Binding with
v-model
: Vue.js supports two-way data binding with thev-model
directive, which is a shorthand for handling both input and output bindings. It automatically updates the data property and the input field when either changes.Example with a simple text input:
<template> <div> <label for="username">Username:</label> <input type="text" id="username" v-model="username" /> <p>Entered Username: {{ username }}</p> </div> </template> <script> export default { data() { return { username: '', }; }, }; </script>
Handling Form Submission: When dealing with forms, you often need to handle form submission. You can use the
@submit
event to capture the form submission event and then perform any necessary actions, such as making an API request.Example with a form submission:
<template> <div> <form @submit.prevent="submitForm"> <label for="email">Email:</label> <input type="email" id="email" v-model="email" /> <label for="password">Password:</label> <input type="password" id="password" v-model="password" /> <button type="submit">Submit</button> </form> </div> </template> <script> export default { data() { return { email: '', password: '', }; }, methods: { submitForm() { // Perform actions like making an API request console.log('Form submitted with:', this.email, this.password); }, }, }; </script>
In the example above, the
@submit.prevent="submitForm"
prevents the default form submission behavior, and thesubmitForm
method is called when the form is submitted.Checkbox and Radio Buttons: For checkboxes and radio buttons, you can use the
v-model
directive as well. The data property will be a Boolean for checkboxes and a string for radio buttons.Example with a checkbox:
<template> <div> <label for="acceptTerms">Accept Terms:</label> <input type="checkbox" id="acceptTerms" v-model="acceptTerms" /> <p>Accepted Terms: {{ acceptTerms }}</p> </div> </template> <script> export default { data() { return { acceptTerms: false, }; }, }; </script>
Select Dropdowns: For select dropdowns, you can use the
v-model
directive to bind the selected option to a data property.Example with a select dropdown:
<template> <div> <label for="country">Select Country:</label> <select id="country" v-model="selectedCountry"> <option value="us">United States</option> <option value="ca">Canada</option> <option value="uk">United Kingdom</option> </select> <p>Selected Country: {{ selectedCountry }}</p> </div> </template> <script> export default { data() { return { selectedCountry: 'us', }; }, }; </script>
These examples cover some of the fundamental aspects of working with form elements in Vue.js 3. Remember that Vue.js provides flexibility, and you can adapt these patterns based on the specific requirements of your application.