V – model principle

V-model is actually syntactic sugar, and here is how syntactic sugar is constructed.

The syntax of the package under the V-Model custom instruction is the value attribute of input and the input event. The whole process is as follows:

<input v-modle="inputV" />
/ / is equivalent to
<input :value="inputV" @input="inputV = $event.target.value"/>
Copy the code
  • Input property binding — the inputV variable, which passes the value to input;
  • Input event, which is displayed in theWhen the input value inputV changesTrigger. When the event is triggered, inputV is reassigned with the value$event.target.value, which is the value of the DOM of the currently triggered input event object, which is the value of the input.

This completes the two-way data binding of the V-Model.

We’ll see that the v-model syntax sugar applies to all custom components of elementUI, as well as select and Textarea in addition to input.

  • Text and Textarea elements: The V-model uses the value attribute to set the initial value and bind variables, and the input event updates the value;

  • Checkbox and Radio elements: The V-model uses the Checked property to set the initial value and bind the variable, and the change event updates the value;

  • Select element: V-model uses value attribute to set initial value and bind variable, change event updates value;

Such as the checkbox:

// It appears to execute a v-model command
<input type="checkbox" v-model="checkedNames">
/ / in fact
<input
  type="checkbox" 
  :value="checkedNames" 
  @change="checkedNames = $event.target.value" 
/>
Copy the code

V-model for custom components

Parent component label

<my-component v-model="myData" />
Copy the code

Subcomponent method, disassembled by value binding and input event updating value.

First, you need to receive a prop of the value in the child component (for value binding, or setting the initial value)

props:{
  value: {type:String.default:' '}}Copy the code

The values are then updated within the component and written to the logical part where the values need to be updated

this.$emit('input', newData);
Copy the code

This is done by getting the value inside the component and manually triggering the input event to update the value, but only by writing the V-model instruction to the parent component, which is also a way of passing the value to the parent component.