V-model tutorial (learning notes)


Official website explanation

expect: varies depending on the form control type.
、 、 、components
.lazy-By default,v-model Every timeinputAfter the event is triggered, the value of the input box is synchronized with the data. Can addlazyModifier so thatchange Events_ After_ Synchronize
.number-If you want to automatically convert the user’s input value to a numeric type, you can add the number modifier to the V-model
.trim-If you want to automatically filter the first and last white space characters entered by the user, you can add the trim modifier to the V-model
usageCreate a two-way binding on a form control or component.

Implementation principle of V-model

Basic Usage

v-modelIt is essentially a syntax sugar. You can use the V-model instruction in the form, andCreate a two-way data binding on the element.

  • It automatically selects the correct method to update the element according to the control type. It is responsible for monitoring user input events to update data, and some special processing for some extreme scenarios.
  • v-model All form elements are ignored value、checked、selectedThe initial value of the property always takes the data of the Vue instance as the data source.
  • The initial value should be declared in the data option of the component through JavaScript.

v-model Use different attributes internally for different input elements and throw different events:

  • Text and textarea elements use value attribute and input event;
  • Checkbox and radio use the checked attribute and change event;
  • The select field takes value as a prop and change as an event.

Use examples

V-model dynamic binding, dynamic options for rendering with V-for:

{{ option.text }}

Selected: {{ selected }}
new Vue({
  el: '...',
  data: {
    selected: 'A',
    options: [
      { text: 'One', value: 'A' },
      { text: 'Two', value: 'B' },
      { text: 'Three', value: 'C' }