Review and consolidate, the use and implementation principle of v-model in vue

The use and implementation principle of v-model


foreword

This article is mainly to review the principle of v-model, including the realization principle of vue2 and vue3.


1. What can v-model do?

1. v-model can be used in <input><select><textarea>and customized components.
2. Create two-way bindings on form controls or components.

Two, usage

1. The two-way binding command can synchronously update the input value of the control on the page to the data attribute of the relevant binding, and will also update the data binding attribute.
2. Used on custom components. See example
vue2 version:

//示例1:
<div id="app">
	<p>{
    
    {
    
    name}}</p>
	<input type="text" v-model="name" />
</div>
data(){
    
    
	return {
    
    
		name: ""
	}
}

//示例2:自定义组件使用v-model
//father component
<com-input v-model="inputValue"></com-input>
<div>{
    
    {
    
    inputValue}}</div>
data () {
    
    
	return {
    
    
		inputValue: ""
	}
}
//child component
<div>
	<input type="text" @input="$emit('myInput', $event.target.value)">
</div>
export default {
    
    
//可以通过model对象自定已prop的名称喝事件
  model: {
    
    
    prop: 'inputValue',//默认value
    event: 'myInput',//默认input
  },
  props: {
    
    
    myValue: String,
  }
}

vue3 version:

//示例1:
<div id="app">
	<p>{
    
    {
    
    name}}</p>
	<input type="text" v-model="name" />
</div>
data(){
    
    
	return {
    
    
		name: ""
	}
}
//示例2:
//father component
<com-input v-model:propValue="inputValue"></com-input>
<div>{
    
    {
    
    inputValue}}</div>
const inputValue = ref('')
//child component
<script>
export default {
    
    
  props: ['propValue'],
  emits: ['update:propValue']
}
</script>
<template>
  <input
    type="text"
    :value="propValue"
    @input="$emit('update:propValue', $event.target.value)"
  />
</template>

3. Implementation principle

If you understand the usage of the above custom components, then you have basically understood the principle of v-model.

v-model If v-model is "disassembled and written" it will be as follows
<input type="text" :value="testValue" @input="testValue = $event.target.value">

Explanation:
1. Define the data attribute, bind the input to the data attribute, listen to the input event and assign a value.
2. Use bound data to realize v-model

//示例:
<div>{
    
    {
    
     testValue}}</div>
<input
  type="text"
  v-bind:value="testValue"
  @input="testValue = $event.target.value"
/>
data() {
    
    
  return {
    
    
    testValue: "",
  };
}
//示例:
//当组件使用的时候
<com-input
  :propValue="inputValue "
  @update:propValue="newValue => inputValue = newValue"
/>

Summarize

This review has learned a lot of forgotten things. If you have any questions, please correct me and learn from each other.

Guess you like

Origin blog.csdn.net/qq_43205326/article/details/125364721