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>
相关推荐
钛态3 小时前
Vite 中的 CSS 工程化:从 CSS Modules 到 UnoCSS 的渐进式迁移
前端·vue·react·web
Csvn5 小时前
原型链、this 与闭包内存:三座深水区一次打通(含内存泄漏排查实战)
前端·javascript
葡萄城技术团队5 小时前
如何通过 JSON 数据源 / Web API 快速构建轻量级报表(Report)?
前端·json·原型模式
万维易源5 小时前
趣味项目素材|免费脑筋急转弯查询接口实战接入教程
javascript·免费api·脑筋急转弯查询·脑筋急转弯接口
浪兎兎5 小时前
【Java Web】Servlet + JSP 笔记
java·前端·servlet
Patrick_Wilson6 小时前
iOS Safari Clipboard API 权限弹窗问题
前端·ios·safari
OpenTiny社区7 小时前
Naive UI × GenUI SDK:自定义物料库搭建实战
前端·ai编程
kyriewen7 小时前
我拿 4 个真实前端任务试了 GLM-5.3 Flash:代码一遍跑通,账单 4 分钱
前端·程序员·ai编程
IT_陈寒7 小时前
Vue的响应式更新有时候真的不听话
前端·人工智能·后端