vuejs
  1. vuejs-component-v-model

VueJS Component v-model Directive

Syntax

<template>
  <input v-model="message">
</template>

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

Example

<template>
  <div>
    <p>{{ message }}</p>
    <MyInput v-model="message" />
  </div>
</template>

<script>
import MyInput from '@/components/MyInput.vue'

export default {
  components: {
    MyInput
  },
  data() {
    return {
      message: ''
    }
  }
}
</script>

Output

The output of the above example will be a parent component and a child component where the parent component App.vue template includes a MyInput which is another custom component and accepts the message prop via v-model.

Explanation

The VueJS Component v-model directive is used to create two-way data bindings on form input, textarea, and select elements. This directive automatically updates the data property that is bound to the input and vice versa.

Use

Use the v-model directive to create two-way data bindings on form elements. When the value of an input, textarea or select element changes, the component’s data property bound to the v-model directive is updated automatically.

v-model is a shorthand for using the value prop and the @input event on form controls.

Important Points

  • The v-model directive is a shortcut for creating two-way data bindings on form elements.
  • For custom components, the v-model directive must be used in conjunction with a value prop and an @input event.
  • The v-model directive should only be used on form elements that accept user input.

Summary

The VueJS Component v-model directive is a powerful way to create two-way data bindings on form elements. This directive updates the data property automatically when the input's value changes, and vice versa. Its usage can greatly simplify the development of forms and related components in a VueJS application.

Published on: