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>
相关推荐
踢足球092922 分钟前
寒假打卡:2026-2-7
java·开发语言·javascript
_果果然23 分钟前
这 7 个免费 Lottie 动画网站,帮你省下一个设计师的工资
前端
QT.qtqtqtqtqt25 分钟前
uni-app小程序前端开发笔记(更新中)
前端·笔记·小程序·uni-app
楚轩努力变强43 分钟前
iOS 自动化环境配置指南 (Appium + WebDriverAgent)
javascript·学习·macos·ios·appium·自动化
Aliex_git1 小时前
跨域请求笔记
前端·网络·笔记·学习
John_ToDebug1 小时前
引擎深处的漫游者:构建浏览器JavaScript引擎的哲学与技艺
javascript·chrome·js
37方寸1 小时前
前端基础知识(Node.js)
前端·node.js
程序猿阿伟1 小时前
《TypeScript中Protobuf到运行时类型安全的转换指南》
javascript·安全·typescript
powerfulhell1 小时前
寒假python作业5
java·前端·python
木子啊2 小时前
前端组件化:模板继承拯救发际线
前端