How to use v model in vue 3

In Vue 3, v-model is a directive that simplifies the process of two-way data binding between form input elements and the component's data

November 23, 20241 min read

Introduction

In Vue 3, v-model is a directive that simplifies the process of two-way data binding between form input elements and the component's data. This means that whenever the user changes the input, the component's data is updated, and the opposite is true.

Usage

<template>
  <input type="text" v-model="message">
  <p>{{ message }}</p>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    }
  }
}
</script>

Here,

  1. v-model="message": This binds the message data property to the input element.
  2. {{ message }}: This displays the current value of the message data property.

Each time the user types in the input, the message data property is updated, and the p tag displays the new value.

Try Kodaschool for free

Click below to sign up and get access to free web, android and iOs challenges.

Sign Up

Using v-model with Other Input Types

v-model can be used with various input types:

  • Text input: type="text"
  • Text area: type="textarea"
  • Checkboxes: type="checkbox"
  • Radio buttons: type="radio"
  • Select elements: <select>

Example with a Select Element:

<template>
  <select v-model="selectedOption">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
  </select>
  <p>Selected option: {{ selectedOption }}</p>
</template>

<script>
export default {
  data() {
    return {
      selectedOption: 'option1'
    }
  }
}
</script>

The selectedOption data property will be updated each time the user selects a different option from the dropdown.

Key Points to Remember:

  • v-model is a powerful tool for creating dynamic forms in Vue 3.
  • It simplifies two-way data binding between form elements and component data.
  • It can be used with various input types, including text, textarea, checkbox, radio, and select.
  • By understanding v-model, you can build more interactive and user-friendly Vue applications

Peace!

Jackson Obere

About Jackson Obere

I enjoy working with front-end technologies like Vue, React, and Vanilla JavaScript, with some Python on the side. I love building interactive web experiences and breaking down tricky concepts to make them easier to understand. I'm always curious and enjoy learning new things in the ever-evolving tech space.