Vue Form Inputs

📝 Vue Form Inputs

Handling form inputs is a core part of building applications in Vue.js.

Vue makes this simple using v-model, which creates two-way data binding between form fields and data.


1️⃣ What are Vue Form Inputs? ⭐

Form inputs allow users to:

  • Enter text

  • Select options

  • Check boxes

  • Submit data

Vue binds these inputs to data using v-model.


2️⃣ v-model (Two-Way Binding) ⭐⭐

<input type="text" v-model="name" />
<p>{{ name }}</p>
export default {
data() {
return {
name: ""
}
}
}

📌 When input changes → data updates
📌 When data changes → input updates


3️⃣ Text Input Example ⭐

<input type="text" v-model="username" placeholder="Enter name" />
data() {
return { username: "" }
}

4️⃣ Textarea Input ⭐

<textarea v-model="message"></textarea>
<p>{{ message }}</p>

5️⃣ Checkbox Input ⭐⭐

Single Checkbox (Boolean)

<input type="checkbox" v-model="isChecked" />
data() {
return { isChecked: false }
}

Multiple Checkboxes (Array)

<input type="checkbox" value="HTML" v-model="skills" /> HTML
<input type="checkbox" value="CSS" v-model="skills" /> CSS
<input type="checkbox" value="Vue" v-model="skills" /> Vue
data() {
return { skills: [] }
}

6️⃣ Radio Button ⭐⭐

<input type="radio" value="Male" v-model="gender" /> Male
<input type="radio" value="Female" v-model="gender" /> Female
data() {
return { gender: "" }
}

7️⃣ Select Dropdown ⭐⭐

Single Select

<select v-model="city">
<option disabled value="">Select City</option>
<option>Delhi</option>
<option>Mumbai</option>
</select>

Multiple Select

<select v-model="cities" multiple>
<option>Delhi</option>
<option>Mumbai</option>
</select>
data() {
return { cities: [] }
}

8️⃣ Number Input & Modifiers ⭐⭐⭐

<input type="number" v-model.number="age" />

Common v-model Modifiers

Modifier Use
.number Convert to number
.trim Remove spaces
.lazy Update on change
<input v-model.trim="name" />

9️⃣ Form Submit Handling ⭐⭐

<form @submit.prevent="submitForm">
<input v-model="email" />
<button>Submit</button>
</form>
methods: {
submitForm() {
console.log(this.email);
}
}

📌 .prevent stops page reload


🔟 Form Validation (Basic) ⭐⭐

<input v-model="email" />
<p v-if="!email">Email required</p>

1️⃣1️⃣ v-model in Vue 3 (Custom Input) ⭐⭐⭐

<MyInput v-model="username" />
props: ["modelValue"],
emits: ["update:modelValue"]

📌 Enables reusable form components


📌 Interview Questions

Q1. What is v-model?
👉 Two-way data binding directive

Q2. Difference between checkbox & radio?
👉 Checkbox → multiple values
👉 Radio → single value

Q3. How to stop form reload?
👉 @submit.prevent

Q4. What does .number modifier do?
👉 Converts input to number


✅ Summary

v-model binds input & data
✔ Supports text, checkbox, radio, select
✔ Modifiers improve data handling
.prevent avoids reload
✔ Forms are reactive in Vue

You may also like...