Vue中v-model原理

Vue中v-model原理

通过父子组件通信揭开v-model实现原理

父子组件通信

App.vue

javascript 复制代码
<template>
  <p>父组件:{{num}}</p>
  <hello-world :num="num" @change="change"></hello-world>
</template>

<script setup>
import {ref} from "vue";
import HelloWorld from "./components/HelloWorld.vue";

const num = ref(0);
function change(value){
  num.value = value;
}

</script>

HelloWorld.vue

javascript 复制代码
<template>
  <p>子组件:{{numProps.num}}</p>
  <button @click="add">add</button>
</template>

<script setup>
const numProps = defineProps({
  num:Number
});
const emit = defineEmits("change");
function add(){
  emit('change',numProps.num+1);
}
</script>

改变变量名称和方法名称

App.vue

javascript 复制代码
<template>
  <p>父组件:{{num}}</p>
  <hello-world :modelValue="num" @update:modelValue="change"></hello-world>
</template>

<script setup>
import {ref} from "vue";
import HelloWorld from "./components/HelloWorld.vue";

const num = ref(0);
function change(value){
  num.value = value;
}

</script>

HelloWorld.vue

javascript 复制代码
<template>
  <p>子组件:{{numProps.modelValue}}</p>
  <button @click="add">add</button>
</template>

<script setup>
const numProps = defineProps({
  modelValue:Number
});
const emit = defineEmits("update:modelValue");
function add(){
  emit('update:modelValue',numProps.modelValue+1);
}
</script>

简写向子组件通信

App.vue

javascript 复制代码
<template>
  <p>父组件:{{num}}</p>
  <hello-world v-model:="num"></hello-world>
</template>

<script setup>
import {ref} from "vue";
import HelloWorld from "./components/HelloWorld.vue";
const num = ref(0);
</script>

简写子组件

HelloWorld.vue

javascript 复制代码
<template>
  <input type="text"
         :value="modelValue"
         @input="(e) => $emit('update:modelValue',e.target.value)"/>
<!--  <input type="text"
         :value="modelValue"
         @input="$emit('update:modelValue',$event.target.value)"/>-->
</template>

<script setup>
defineProps({
  modelValue:Number
});
defineEmits("update:modelValue");

</script>
相关推荐
天天打码1 分钟前
Nuxt.js一个基于 Vue.js 的通用应用框架
前端·javascript·vue.js
Dnn014 分钟前
前端读取本地项目中 public/a.xlsx 文件中的数据 vue3
前端·javascript·vue.js·读取xlsx数据
一块小砖头儿21 分钟前
HTML向四周扩散背景
前端·javascript·html
CodeClimb26 分钟前
【华为OD-B卷-打印文件 100分(python、java、c++、js、c)】
java·javascript·c++·python·华为od
陳長生.26 分钟前
JAVA EE(进阶)_HTML
javascript·css·java-ee·html
杨超越luckly27 分钟前
HTML应用指南:利用POST请求获取全国申通快递服务网点位置信息
大数据·前端·信息可视化·数据分析·html
Allen Bright28 分钟前
【HTML-1】HTML骨架标签:构建网页的基础框架
前端·html
OneT1me1 小时前
SN生成流水号并且打乱
java·linux·前端
眼镜chen1 小时前
luckysheet的使用——17.将表格作为pdf下载到本地
前端·javascript·vue.js·chrome·pdf
_oP_i1 小时前
python实现pdf转图片(针对每一页)
前端·数据库·python