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" />
相关推荐
薛一半3 分钟前
React的数据绑定
前端·javascript·react.js
爱看书的小沐4 分钟前
【小沐杂货铺】基于Three.js渲染三维无人机Drone(WebGL / vue / react )
javascript·vue.js·react.js·无人机·webgl·three.js·drone
天若有情6732 小时前
从 try-catch 回调到链式调用:一种更优雅的 async/await 错误处理方案
前端·异常处理·前端开发·async·异步·await·异步编程
xuzhiqiang07245 小时前
Java进阶之路,Java程序员职业发展规划
java·开发语言
MediaTea6 小时前
Python:生成器表达式详解
开发语言·python
ShenJLLL7 小时前
vue部分知识点.
前端·javascript·vue.js·前端框架
overmind8 小时前
oeasy Python 115 列表弹栈用pop删除指定索引
开发语言·python
恋猫de小郭8 小时前
你是不是觉得 R8 很讨厌,但 Android 为什么选择 R8 ?也许你对 R8 还不够了解
android·前端·flutter
PineappleCoder8 小时前
告别“幻影坦克”:手把手教你丝滑规避布局抖动,让页面渲染快如闪电!
前端·性能优化
Never_Satisfied8 小时前
在c#中,使用windows自带功能将文件夹打包为ZIP
开发语言·windows·c#