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" />
相关推荐
祝余呀5 分钟前
HTML初学者第三天
前端·html
就爱瞎逛21 分钟前
TailWind CSS Intellisense 插件在VSCode 上不生效
前端·css·vscode·tailwind
念九_ysl22 分钟前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
柚子81624 分钟前
sibling-index:我用这个画时钟表盘
前端·css
yaoxin52112331 分钟前
124. Java 泛型 - 有界类型参数
java·开发语言
UI设计和前端开发从业者39 分钟前
UI前端大数据处理策略优化:基于云计算的数据存储与计算
前端·ui·云计算
liulilittle1 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师1 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
勤奋的知更鸟1 小时前
Java 编程之模板方法模式
java·开发语言·模板方法模式
前端小巷子1 小时前
Web开发中的文件上传
前端·javascript·面试