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>
相关推荐
Coder_Boy_3 小时前
【Java核心】企业级高并发系统底层设计思想
java·前端·数据库·spring boot·高并发
程序哥聊面试3 小时前
第一课:React的Hooks
前端·javascript·react.js
沄媪3 小时前
Web渗透测试详细技术总结(基于Kali Linux)
linux·前端·渗透测试·web
东东5163 小时前
基于SSM的宠物医院预约挂号系统的设计与实现vue
java·前端·javascript·vue.js·毕设
黑贝是条狗3 小时前
mormor2与vue搭建一个博客系统
前端·javascript·vue.js
拔刀能留住落樱吗、3 小时前
代码诊疗室——疑难Bug破解战
前端·html
GISer_Jing3 小时前
Taro 5.0 深度:跨端开发的架构革新与全阶实践指南
前端·react.js·taro
宁雨桥3 小时前
我开源了一个 Chrome 插件:一键总结网页为 Markdown
前端·chrome·开源
南夏一木子3 小时前
Vue学习 —— Axios异步通信
前端·vue.js·学习
GISer_Jing4 小时前
Taro 5.0 小白快速上手指南:从0到1实现跨端开发
前端·react.js·taro