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 分钟前
优化前端性能必读:浏览器渲染流程原理全揭秘
前端·浏览器
Data_Adventure7 分钟前
Vue 3 手机外观组件库
前端·github copilot
泯泷13 分钟前
Tiptap 深度教程(二):构建你的第一个编辑器
前端·架构·typescript
lilv6614 分钟前
python中用xlrd、xlwt读取和写入Excel中的日期值
开发语言·python·excel
屁__啦19 分钟前
前端错误-null结构
前端
lichenyang45319 分钟前
从0开始的中后台管理系统-5(userList动态展示以及上传图片和弹出创建用户表单)
前端
未来之窗软件服务24 分钟前
解析 div 禁止换行与滚动条组合-CSS运用
前端·css
不远处的小阿秋44 分钟前
2025年,前端还需要虚拟DOM吗
前端
DcTbnk1 小时前
tailwindcss、postcss、autoprefixer,这三个分别是干嘛的
前端
zReadonly1 小时前
antdv@4.x在360极速浏览器兼容解决办法
前端