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" />
相关推荐
软件技术NINI几秒前
HTML——基本标签
前端·javascript·html
DreamByte18 分钟前
Python Tkinter小程序
开发语言·python·小程序
卡兰芙的微笑24 分钟前
get_property --Cmakelist之中
前端·数据库·编辑器
覆水难收呀27 分钟前
三、(JS)JS中常见的表单事件
开发语言·前端·javascript
阿华的代码王国31 分钟前
【JavaEE】多线程编程引入——认识Thread类
java·开发语言·数据结构·mysql·java-ee
猿来如此呀34 分钟前
运行npm install 时,卡在sill idealTree buildDeps没有反应
前端·npm·node.js
繁依Fanyi37 分钟前
828 华为云征文|华为 Flexus 云服务器部署 RustDesk Server,打造自己的远程桌面服务器
运维·服务器·开发语言·人工智能·pytorch·华为·华为云
hw_happy40 分钟前
解决 npm ERR! node-sass 和 gyp ERR! node-gyp 报错问题
前端·npm·sass
FHKHH44 分钟前
计算机网络第二章:作业 1: Web 服务器
服务器·前端·计算机网络
weixin_486681141 小时前
C++系列-STL容器中统计算法count, count_if
开发语言·c++·算法