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" />
相关推荐
刺客-Andy7 分钟前
CSS中使用 HSL(Hue, Saturation, Lightness) 动态生成色值
前端·css·前端框架·vue
南北是北北8 分钟前
为什么“以音频为主时钟”最稳,怎么做 A/V 同步
前端·面试
大翻哥哥9 分钟前
Python 2025:AI代理、Rust与异步编程的新时代
开发语言·人工智能·python
leon_teacher10 分钟前
ArkUI核心功能组件使用
android·java·开发语言·javascript·harmonyos·鸿蒙
小奋斗12 分钟前
深入浅出:模板引擎详解
javascript·面试
LHX sir15 分钟前
巨头撤退,玩家内卷!2025,IoT平台的生死劫与重生路
开发语言·前端·物联网·低代码·ui·前端框架·交互
龙在天16 分钟前
Tailwind 类名 记个规律大概,然后去文档查
前端
百锦再17 分钟前
Python:AI开发第一语言的全面剖析
java·开发语言·人工智能·python·sql·ai·radis
Undoom26 分钟前
当Python遇见高德:基于PyQt与JS API构建桌面三维地形图应用实战
javascript·后端
东北南西32 分钟前
实现 TypeScript 内置工具类型(源码解析与实现)
前端·typescript