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 分钟前
Cursor操作面板改为垂直
前端
我要让全世界知道我很低调8 分钟前
记一次 Vite 下的白屏优化
前端·css
threelab8 分钟前
three案例 Three.js波纹效果演示
开发语言·javascript·ecmascript
1undefined210 分钟前
element中的Table改造成虚拟列表,并封装成hooks
前端·javascript·vue.js
paopaokaka_luck32 分钟前
基于SpringBoot+Vue的非遗文化传承管理系统(websocket即时通讯、协同过滤算法、支付宝沙盒支付、可分享链接、功能量非常大)
java·数据库·vue.js·spring boot·后端·spring·小程序
蓝倾1 小时前
淘宝批量获取商品SKU实战案例
前端·后端·api
comelong1 小时前
Docker容器启动postgres端口映射失败问题
前端
花海如潮淹1 小时前
硬件产品研发管理工具实战指南
前端·python
用户3802258598241 小时前
vue3源码解析:依赖收集
前端·vue.js
用户7579419949701 小时前
基于JavaScript的简易Git
javascript