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>
相关推荐
鸠摩智首席音效师16 分钟前
如何清除 Yarn 缓存 ?
javascript
写不来代码的草莓熊25 分钟前
vue前端面试题——记录一次面试当中遇到的题(5)
前端
weixin_ab42 分钟前
【HTML分离术】
前端·html
文心快码BaiduComate1 小时前
新手该如何选择AI编程工具?文心快码Comate全方位体验
前端·后端·程序员
夫唯不争,故无尤也1 小时前
Tomcat 内嵌启动时找不到 Web 应用的路径
java·前端·tomcat
lichong9511 小时前
【Xcode】Macos p12 证书过期时间查看
前端·ide·macos·证书·xcode·大前端·大前端++
oh,huoyuyan1 小时前
如何在火语言中指定启动 Chrome 特定用户配置文件
前端·javascript·chrome
前端大聪明20021 小时前
single-spa原理解析
前端·javascript
一枚前端小能手1 小时前
📦 从npm到yarn到pnpm的演进之路 - 包管理器实现原理深度解析
前端·javascript·npm
影i1 小时前
CSS Transform 和父元素撑开问题
前端