The difference between v-model and v-bind:value in Vue and manual implementation of v-model

The following are examples of input:

1. The difference between v-model and v-bind:value in Vue

1. v-model

//html
<div>
   <input type="text" v-model="message" />
   <div>{
   
   {message}}</div>
</div>

//js
export default {
  data(){
      return{
       message:'123'
      }
  }, 
}

When modifying the data in the input box, the message in the data will also change accordingly, so "123456" is displayed up and down 

2. v-bind:value

//html
<div>
   <input type="text" v-bind:value="message" />
   <div>{
   
   {message}}</div>
</div>

//js
export default {
  data(){
      return{
       message:'123'
      }
  }, 
}

 

It can be seen that when the value in the input box is modified, the message in the data has not been changed, so the original "123" is still displayed in {{message}}

summary:

(1) v-model realizes the two-way binding of data in the view and data. One of the two changes, and the other will also change accordingly.

(2) v-bind:value only binds the data in data to the input during initialization. Modifying the value of input will not change the data in data.

 

2. Manually implement v-model (v-bind:value+event)

Note: Both input change and input events can be implemented. The difference is that input is triggered in real time while change is triggered when the focus is lost or when you press Enter.

(Actually, by default,  the value and data of the input box are synchronized v-model in the  inputevent, but you can add a modifier  lazy to change to change synchronization in the  event)

Because we want the effect of real-time changes, so here we choose to listen to the input event

//html
<div>
     <input type="text" @input="handleInput" :value="message" />
     <div>{
   
   {message}}</div>
     
</div>

//js
export default {
  data(){
      return{
       message:'123'
      }
  }, 
  methods:{
    handleInput(e){
      this.message = e.target.value;
    }
  }
}

Or simply abbreviate:

<input type="text" @input="message=$event.target.value" :value="message" />

Principle of v-model:

v-model is actually a syntactic sugar. It essentially contains two operations :

  • v-bind binds a value attribute
  • The v-on instruction binds the input event to the current element

 

 

Guess you like

Origin blog.csdn.net/a1059526327/article/details/108981613