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>
相关推荐
zhangxingchao19 分钟前
Flutter中的页面跳转
前端
前端风云志40 分钟前
TypeScript实用类型之Omit
javascript
烛阴1 小时前
Puppeteer入门指南:掌控浏览器,开启自动化新时代
前端·javascript
全宝2 小时前
🖲️一行代码实现鼠标换肤
前端·css·html
小小小小宇2 小时前
前端模拟一个setTimeout
前端
萌萌哒草头将军2 小时前
🚀🚀🚀 不要只知道 Vite 了,可以看看 Farm ,Rust 编写的快速且一致的打包工具
前端·vue.js·react.js
芝士加3 小时前
Playwright vs MidScene:自动化工具“双雄”谁更适合你?
前端·javascript
Carlos_sam4 小时前
OpenLayers:封装一个自定义罗盘控件
前端·javascript
前端南玖4 小时前
深入Vue3响应式:手写实现reactive与ref
前端·javascript·vue.js
wordbaby4 小时前
React Router 双重加载器机制:服务端 loader 与客户端 clientLoader 完整解析
前端·react.js