Vue3 组件双向绑定的两种方法

defineProps 和 defineEmits

案例:

html 复制代码
# child
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <input
    :value="props.modelValue"
    @input="emit('update:modelValue', $event.target.value)"
  />
</template>
html 复制代码
# father
<Child
  :modelValue="foo"
  @update:modelValue="$event => (foo = $event)"
/>

defineModel

Vue 官网 是这样描述的:从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 因此,以后这个是实现组件双向绑定的首选。

案例:

html 复制代码
# child

<template>
  <div>Parent bound v-model is: {{ model }}</div>
  <button @click="update">Increment</button>
</template>

<script setup>
const model = defineModel()

function update() {
  model.value++
}
</script>
html 复制代码
# father

<Child v-model="countModel" />
相关推荐
QuantumStack40 分钟前
【C++ 真题】P1104 生日
开发语言·c++·算法
安全系统学习1 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
whoarethenext1 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
涛哥码咖1 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖1 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水2 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐2 小时前
零基础学HTML和CSS:网页设计入门
前端·css
代码的奴隶(艾伦·耶格尔)2 小时前
后端快捷代码
java·开发语言
老虎06272 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
三水气象台2 小时前
用户中心Vue3网页开发(1.0版)
javascript·css·vue.js·typescript·前端框架·html·anti-design-vue