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" />
相关推荐
明月_清风25 分钟前
自定义右键菜单:在项目里实现“选中文字即刻生成新提示”
前端·javascript
明月_清风26 分钟前
告别后端转换:高质量批量导出实战
前端·javascript
刘发财5 小时前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
牛奶7 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶8 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
Kagol10 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
GIS之路11 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide11 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
ssshooter12 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
格砸12 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端