SoFunction
Updated on 2025-04-07

Analysis of the principle of vue native input input box

text

First, let's look at a piece of code:

<input value="value">

Here is a nativeinputInput box, each native input box will have onevalueThe properties of the latest data used for input are used.

If we want to get this value we can passOr by$to get the stored value.

As long as the user enters data, theninputThe tag will put the input data into thisvalueMedium (new data will overwrite old data, so what we get is the latest).

Now let's look at the above tags, we'reinputA tag addedvalueAttributes and assignments'value'. Actually set on the tagvalueAttributes have two functions:

  • Created in the first timeinputWhen tagging, display the corresponding initial value in the input box (no data is displayed in the input box without this attribute)
  • usevalueInitialize the initial value of the attribute(When there is no such propertyis an empty string)

The above code means addingvalue="value"Attributes, initializationand display the initial value in the corresponding input box

It should be noted here that in subsequent user input operations, the data in the input box is just to let the user see what he has entered, that's all. Someone can have questions, isn't itWhat is in it, so what is displayed in the input box? Actually not.

What to display in the input box andThere is no direct contact, and the display in the input box is just to facilitate the user to see what he has entered.

summary:

inputIn-housevalueThere are two types:value="xxx"andWe need to know what the two functions do. What roles do they play in the entire input display process?

Now let's take a look at itvueIn the input box, let's first look at a piece of code:

<input
   v-bind:value
   @input="value = $"
/>
data(){
    return {
          value:'123'
    }
}

We generally usev-bind:valueCome toInputTag binding to avueHere we are bound to. Herev-bind:value === :value="value". The principle of this implementation is relatively simple.

First we defineBecauseBounded to:valueso the value we specified will be displayed in the input box at the beginning, that is,'123'. After we enter the data,$(Here$that is) will store the latest input value and assign the latest value to

becauseChanged, at this timevueUpdate the page, and then update itinputof:valueIt is the latest value.

But there is a problem here, that is<input>It will not be destroyed and rebuilt, that is, = $Just changedIf quoted elsewhere, then the changes will be made simultaneously. SoUpdated:value="value"What is the impact? Actually, it has no impact.

Because we said earlier:valueThere are two functions: one is initializationThe second is to render the initial value into the corresponding input box. At the beginningAs the initial valueand displayed in the box, his task has been completed, and subsequent changes are:valueIt doesn't matter at all.

actually:value="value"The only function is toBind and display as initial valueinputsuperior.

v-model

Now the calculation of the original element is done with two-way data binding. So how to implement bidirectional data binding between parent and child components Hum? At this point we need to use v-model in our child components. The use of v-model will not be described here. Here we only discuss how to implement v-model in custom components. According to the description of vue's official website, we roughly know that the essence of v-model is syntactic sugar, that is:

&lt;input type="text" v-model="name"&gt;
Equivalent to:
&lt;input type="text" :value="name" @input="name = $"&gt;

vueListen to the input box input behavior and change the corresponding value. How to implement bidirectional data binding to subcomponents? The bidirectional data binding here refers to the parent component passing the value to the child component for use, and the child component can change the value of the parent component. In fact, the above two-way binding can be passed throughv-bind: = 'xxx'To achieve it. In addition to the above methods, andVueWe also provide another way:

&lt;!-- Parent component.vue --&gt;
&lt;child-component :propName="data" @change="change" /&gt;
export default {
    data(){
     data:'123'
  },
  methods:{
     change(value){
         = value
     }
  }
}
//How to change the value of the parent component in the component, then start the corresponding event directly:this.$emit('change', newValue )

existvueIn, it simplifies the above method and we can usev-modelTo perform bidirectional data binding to subcomponents. For example:

&lt;child-component v-model="pageTitle" /&gt;
&lt;!-- It is the abbreviation below: --&gt;
&lt;child-component :value="pageTitle" @input="pageTitle = $event" /&gt; 

By defaultv-modelThe trigger event name isinput. If you want to use a child component, you need to define a name calledvalueofpropOnly use it. To change this value in a child component, you only need to define a function and execute it if necessarythis.$emit('input', newValue) Just do it.

HerenewValuethat is$event. This will change the corresponding value. Except for the default one, of coursevalueandinputName ofvueWe also gave us a more flexible approach.

&lt;!-- Parent component --&gt;
&lt;child-component v-model="pageTitle" /&gt;
//Subcomponentexport default {
  model: {
    prop: 'title', //This is equivalent to an alias, and other names can be given here    event: 'change' //This is equivalent to an alias for the event, and other names can be given here  },
  props: {
    // This will allow the `value` property to be used for other purposes    value: String,
    // Use `title` instead of `value` as the prop of model    title: {
      type: String,
      default: 'Default title'
    }
  }
}

When we want to change the value passed in the child component, then we canthis.$emit('change', newValue)

So, in this examplev-modelIt is the abbreviation of the following:

<child-component :title="pageTitle" @change="pageTitle = $event" />

In essence, thetwowayFactorThis mixed-in-the-configuration class essentially does the above operations.

  @Prop()
  @Model('valueChanged')
      bindValue!: T;

The purpose of this is tov-modelIncomingpropChange tobindValue. Then, the default event name is frominputChange tovalueChange. Next set upget/set

        get currentValue() {
            return ;
        }
        set currentValue(value) {
            this.$emit('valueChanged', value);
        }

The purpose of this is to localize the data. Define a component inside acurrentValueThen set the valueget, when visitingcurrentValueEquivalent to visitv-modelofprop. Then setset. When changingcurrentValueWhen the value of , the corresponding event will be triggered. When triggered, the value in the parent component will change. This implements two-way data binding.

We can see that,The function isv-modelSyntax sugar for operation. It's nothing special, it justv-modelAccess and changes to incoming data are simplified, and are concentrated with a value

The above is the detailed analysis of the principle of vue native input input box. For more information about vue native input input box, please pay attention to my other related articles!