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" />
相关推荐
大时光15 小时前
js 封装 动画效果
前端
大时光15 小时前
html翻页时钟 效果
前端
大猫子的技术日记15 小时前
2025 AI Agent 开发实战指南:从上下文工程到多智能体协作
前端·人工智能·bootstrap
前端达人15 小时前
被JavaScript忽视的Web Animations API:为什么说它是前端动画的真正未来?
开发语言·前端·javascript·ecmascript
忧郁的橙子.15 小时前
04-从零搭建本地AI对话系统:Ollama + DeepSeek-R1:7B + Streamlit
前端·chrome
米羊12115 小时前
风险评估文档记录
开发语言·网络·php
摘星编程16 小时前
解锁Agent智能体的未来:五大实战策略彻底革新人机协作模式
java·开发语言
PTC16 小时前
做了个 EPUB 阅读器,被「阅读进度同步」折磨了一周,总结 4 个血泪教训
前端
Aerkui16 小时前
Go 泛型(Generics)详解
开发语言·后端·golang