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>
相关推荐
用户11977079480735 分钟前
GitHub 电商开源项目分享:用 sharp 批量出饰品主图,试了裁剪、细节图和色彩配置文件三个坑
前端·node.js
deli00710 分钟前
地图定位为什么偏了 500 米?GPS 与火星坐标实测
前端
TK泰妞12 分钟前
节日促销前,TikTok 商品视频应该提前准备什么?
前端·人工智能·节日
CCIE-Yasuo24 分钟前
网络安全-学习web开发-列表、标签
前端·学习·web安全
小大宇28 分钟前
Vue知识点-ElementPlus-06 单选+多选+下拉+日期选择
前端·vue.js·elementui
用户114818678948430 分钟前
Nuxt 3 学习版 Demo:跟着做一遍,从跑起来到自己会改
前端
hiahiahia1231 小时前
Streaming Model Output
开发语言·前端
paopaokaka_luck1 小时前
基于springboot+vue的益暖微光公益服务平台(DeepSeek公益助手、善款信息追溯、志愿服务积分闭环、ECharts运营分析、活动状态自动流转)
java·前端·javascript·spring boot·mysql·架构·echarts
栀椩1 小时前
Electron 内嵌页面跨域问题(CORS/PNA)解决全记录
前端·javascript·electron
asaotomo1 小时前
截图识题、AI 讲解、笔记沉淀:Chrome 扩展体验
前端·chrome·笔记