Vue3 v-model Directive

Vue3 内置指令Vue3 Built-in Directives


v-modelThe directive is used to create two-way data binding on form input elements and components.


Basic Description

v-modelThe directive creates two-way data binding on form elements and components. It automatically selects the correct method to update the element based on the control type.

  • Expected Type: Varies depending on the form element type
  • Function: Creates two-way data binding on form input elements and components.

Basic Usage

1. Text Input

Example

<template>
  <div>
    <input v-model="message" placeholder="Input content" />
    <p>Input content: {{ message }}</p>
  </div>
</template>

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

2. Checkbox

Example

<template>
  <div>
    <input type="checkbox" id="agree" v-model="agreed" />
    <label for="agree">I agree to the terms</label>
    <p>Agreed: {{ agreed }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return { agreed: false }
  }
}
</script>

Modifiers

  • .lazy: Syncs after the change event (rather than input)
  • .number: Automatically converts to number
  • .trim: Automatically trims leading/trailing spaces

Example

<input v-model.lazy="lazyInput" placeholder="Sync on blur" />
<input v-model.number="age" type="number" placeholder="Auto convert to number" />
<input v-model.trim="username" placeholder="Trim spaces" />

Vue3 内置指令Vue3 Built-in Directives

Other Extensions