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" />
相关推荐
Mike_jia7 分钟前
LogWhisperer 全解析:打造你的Linux服务器AI日志分析中枢
前端
网安Ruler8 分钟前
崭新出厂,自研CipherForge小工具,攻破 D-Link M30 固件加密
前端·网络·python
daxiang120922059 分钟前
记一次前端请求报错:Content-Length can‘t be present with Transfer-Encoding,+Cursor使用教训
前端·cursor
喵了meme9 分钟前
C语言实战3
c语言·开发语言
武清伯MVP9 分钟前
深入了解Canvas:HTML5时代的绘图利器(二)
前端·html5·canvas
float_六七11 分钟前
Spring AOP表达式速查手册
前端·javascript·spring
Cigaretter713 分钟前
Day 31 类的装饰器
开发语言·python
PineappleCoder13 分钟前
没 CDN = 用户等半天?四大核心机制:就近、分流、提速、容错全搞定
前端·性能优化
DsirNg14 分钟前
JavaScript 事件循环机制详解及项目中的应用
开发语言·javascript·ecmascript
suoyue_zhan16 分钟前
GBase 8s V8.8 安装部署实践指南
前端·数据库·chrome