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" />
相关推荐
勇往直前plus1 小时前
从文件到屏幕:Python/java 字符编码、解码、文本处理的底层逻辑解析
java·开发语言·python
无限进步_1 小时前
面试题 02.04. 分割链表 - 题解与详细分析
c语言·开发语言·数据结构·git·链表·github·visual studio
zh_xuan1 小时前
kotlin Flow的用法
android·开发语言·kotlin·协程·flow
Mr YiRan5 小时前
C++面向对象继承与操作符重载
开发语言·c++·算法
huohaiyu5 小时前
从URL到页面的完整解析流程
前端·网络·chrome·url
阿星AI工作室7 小时前
一个简单Demo彻底理解前后端怎么连的丨Figma + Supabase + Vercel
前端·人工智能
aircrushin7 小时前
一拍即传的平替,完全免费的实时照片墙!
前端
一只鹿鹿鹿7 小时前
智慧水利一体化建设方案
大数据·运维·开发语言·数据库·物联网
没有医保李先生9 小时前
字节对齐的总结
java·开发语言
鹏北海9 小时前
JSBridge 原理详解
前端