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" />
相关推荐
马猴烧酒.1 天前
【团队空间|第十一天】基础功能实现,RBAC权限控制,ShardingSphere详解
java·开发语言·数据库
●VON1 天前
React Native for OpenHarmony:深入剖析 Switch 组件的状态绑定、无障碍与样式定制
javascript·学习·react native·react.js·von
fengxin_rou1 天前
从 String 到 Zset:Redis 核心数据结构全解析及排行榜应用
java·开发语言·redis·多线程
Re.不晚1 天前
Java进阶之路--线程最最详细讲解
java·开发语言
梵刹古音1 天前
【C语言】 数组基础与地址运算
c语言·开发语言·算法
wuguan_1 天前
C#/VP联合编程之绘制图像与保存
开发语言·c#
Howrun7771 天前
C++_错误处理
开发语言·c++
时光追逐者1 天前
一个基于 .NET + Vue 实现的通用权限管理平台(RBAC模式),前后端分离模式,开箱即用!
前端·vue.js·c#·.net·.net core
Aotman_1 天前
Vue el-table 表尾合计行
前端·javascript·vue.js·elementui·前端框架·ecmascript
bubiyoushang8881 天前
基于MATLAB的局部特征尺度分解(LCD)实现与优化
开发语言·matlab