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" />
相关推荐
OpenTiny社区6 分钟前
TinyEngine 低代码实时协作揭秘:原理 +实操,看完直接用!
前端·vue.js·低代码
likuolei6 分钟前
XML 元素 vs. 属性
xml·java·开发语言
X***489610 分钟前
C源代码生成器
c语言·开发语言
梁正雄16 分钟前
2、Python流程控制
开发语言·python
catchadmin40 分钟前
PHP True Async RFC 被拒——原生异步离 PHP 还有多远?
开发语言·php
J***793941 分钟前
PHP在电商中的Magento
开发语言·php
5***790042 分钟前
Vue项目性能优化
前端·javascript·vue.js
丫丫7237341 小时前
Three.js 模型树结构与节点查询学习笔记
javascript·webgl
车传新1 小时前
Javascript
javascript
python零基础入门小白1 小时前
【万字长文】大模型应用开发:意图路由与查询重写设计模式(从入门到精通)
java·开发语言·设计模式·语言模型·架构·大模型应用开发·大模型学习