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" />
相关推荐
Wang's Blog31 分钟前
Java 项目实战: 交友项目 - FastDFS:入门案例
java·开发语言·交友
LucianaiB1 小时前
【元宝搜索开发者征文大赛】AI时代,学得慢就不用学?用元宝搜索打造一个教程保质期,确保每一个教程符合你的现状
前端·人工智能·ai编程
apcipot_rain1 小时前
C++转Java日记(03)
java·开发语言·c++
excel1 小时前
JavaScript 对象池:减少高频对象创建与 GC 压力
前端
布莱克6052 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_6782 小时前
深挖C++:类和对象(中)
开发语言·c++
灿飞屋2 小时前
Rust 编程其实很简单
开发语言·rust
陈随易3 小时前
纯 Go 写的 JS 引擎,跑分超过了 C 语言的 QuickJS
前端·后端·程序员
MOONICK4 小时前
QT元数据
开发语言·qt
D e re k ZH4 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法