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" />
相关推荐
还有你Y3 小时前
Shell 脚本语法
前端·语法·sh
踩着两条虫4 小时前
如何评价VTJ.PRO?
前端·架构·ai编程
2401_873479405 小时前
如何利用IP查询定位识别电商刷单?4个关键指标+工具配置方案
开发语言·tcp/ip·php
Mh5 小时前
鼠标跟随倾斜动效
前端·css·vue.js
我爱cope6 小时前
【从0开始学设计模式-10| 装饰模式】
java·开发语言·设计模式
菜鸟学Python6 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
小码哥_常6 小时前
Kotlin类型魔法:Any、Unit、Nothing 深度探秘
前端
浪浪小洋7 小时前
c++ qt课设定制
开发语言·c++
charlie1145141917 小时前
嵌入式C++工程实践第16篇:第四次重构 —— LED模板,从通用GPIO到专用抽象
c语言·开发语言·c++·驱动开发·嵌入式硬件·重构
故事和你917 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论