复习巩固,vue中v-model的使用及实现原理

v-model的使用及实现原理


前言

本篇文章主要是复习一下,v-model的原理,包括vue2和vue3的实现原理。


一、v-model能干什么

1、v-model可以用在<input><select><textarea>和自定已组件中。
2、在表单控件或者组件上创建双向绑定。

二、用法

1、双向绑定的指令,能将页面上控件输入的值同步更新到相关绑定的data属性,也会在更新data绑定属性。
2、用在自定已组件上。见示例
vue2版本:

//示例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版本:

//示例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>

三、实现原理

如果看懂了上面自定组件的用法,那么你基本已经理解了v-model的原理是什么了。

v-model 如果将v-model “拆开来写” 就会使如下
<input type="text" :value="testValue" @input="testValue = $event.target.value">

解释:
1、定义data属性,input绑定data属性,监听input事件并赋值。
2、使用绑定数据,实现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"
/>

总结

这次复习又学习到不少忘记的东西,如有问题欢迎指正,互相学习。

猜你喜欢

转载自blog.csdn.net/qq_43205326/article/details/125364721