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" />
相关推荐
灵感__idea5 小时前
Hello 算法:“走一步看一步”的智慧
前端·javascript·算法
清水白石0086 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
吴文周6 小时前
告别重复劳动:一套插件让 AI 替你写代码、修Bug、做测试、上生产
前端·后端·ai编程
Mh6 小时前
我决定写一个 3D 地球仪来记录下我要去的地方
前端·javascript·动效
yaoxin5211237 小时前
390. Java IO API - WatchDir 示例
java·前端·python
懒狗小前端7 小时前
做了一个 codex 的中文文档网站,做的不好可以随便喷
前端·后端
. . . . .8 小时前
ref、useRef 和 forwardRef
前端·javascript·react.js
Halo_tjn8 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色8 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手8 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift