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" />
相关推荐
有点。8 分钟前
C++二叉树(一)
开发语言·数据结构·c++
民乐团扒谱机15 分钟前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
报错小能手25 分钟前
Go 语言结构 基础语法
开发语言·后端·golang
Lazionr25 分钟前
stack与queue:底层实现与容器适配器
开发语言·数据结构·c++
张元清1 小时前
React useLatest Hook:在异步回调里读到最新状态 (2026)
javascript·react.js
Hello_Damon_Nikola1 小时前
CH573从入门到精通
c语言·开发语言·单片机·嵌入式硬件
Logintern091 小时前
Langgraph使用MemorySaver建立有记忆的图
开发语言·windows·python
CAD老兵1 小时前
让 AI Coding Agent 直接访问 CAD 文档:GitMCP 实战指南
前端·人工智能·github
豆沙沙包?1 小时前
C++~~~vector容器(p31-P40)
开发语言·c++
程序员鱼皮1 小时前
DeepSeek Harness 最新邪修曝光!被吹成核弹的极简模式,真的夯吗?
前端·后端·ai编程