当前位置: 首页 > news >正文

vue3中父子组件的双向绑定defineModel详细使用方法

文章目录

      • 一、defineProps() 和 defineEmits()
      • 二、defineModel() 的双向绑定
        • 2.1、基础示例
        • 2.2、定义类型
        • 2.3、声明prop名称
        • 2.4、其他声明
        • 2.5、绑定多个值
        • 2.6、修饰符和转换器
        • 2.7、修饰符串联

一、defineProps() 和 defineEmits()

组件之间通讯,通过 props 和 emits 进行通讯,是单向数据流,
子组件不能改变父组件传递给它的 prop 属性,推荐的做法是它抛出事件,通知父组件自行改变绑定的值。

为了在声明 props 和 emits 选项时获得完整的类型推导支持,我们可以使用 defineProps 和 defineEmits API,它们将自动地在 <script setup> 中可用:

  • 父组件:
<template><div><ChildMy v-model:count="count" />{{ count }}</div>
</template><script setup>import ChildMy from './child.vue'import { ref } from 'vue' const count = ref(1)
</script>
  • 子组件:
<template><div>{{ props.count }}<button @click="updatedCount">child btn</button></div>
</template><script setup>
const props = defineProps(["count"]);
const emit = defineEmits(["update:count"]);const updatedCount = () => {emit('update:count', props.count + 1)
}
</script>
  • defineProps 和 defineEmits 都是只能在

二、defineModel() 的双向绑定

这个宏可以用来声明一个双向绑定 prop,通过父组件的 v-model 来使用。

在底层,这个宏声明了一个 model prop 和一个相应的值更新事件。如果第一个参数是一个字符串字面量,它将被用作 prop 名称;否则,prop 名称将默认为 “modelValue”。在这两种情况下,你都可以再传递一个额外的对象,它可以包含 prop 的选项和 model ref 的值转换选项。

defineModel() 的双向绑定是在编译之后,创建了一个model的ref变量以及一个modelValue的props,并且watch了props中的modelValue;当子组件中的modelValue更新时,会触发update:modelValue事件,当父组件接收到这个事件时候,同时更新父组件的变量。

2.1、基础示例
  • 父组件:
<template><div><ChildMy v-model="message"/>{{ message }}</div>
</template><script setup>import ChildMy from './child.vue'import { ref } from 'vue' const message = ref('hello')
</script>
  • 子组件:
<template><div>{{ message }}<button @click="updatedMsg">child btn</button></div>
</template><script setup>
const message = defineModel()const updatedMsg = () => {message.value = `world`
}
</script>
2.2、定义类型
  • 子组件:
<template><div>{{ message }}<button @click="updatedMsg">child btn</button></div>
</template><script setup>
const message = defineModel({ type: String })const updatedMsg = () => {message.value = `world`
}
</script>
2.3、声明prop名称
  • 父组件:
<template><div><ChildMy v-model:count="count"/>{{ count }}</div>
</template><script setup>import ChildMy from './child.vue'import { ref } from 'vue' const count = ref(1)
</script>
  • 子组件:
<template><div>{{ count }}<button @click="updatedCount">child btn</button></div>
</template><script setup>
const count = defineModel("count")
const updatedCount = () => {count.value ++
}
</script>
2.4、其他声明
  • 子组件:
<template><div>{{ count }}<button @click="updatedCount">child btn</button></div>
</template><script setup>
const count = defineModel("count", { type: Number, default: 0 , required: true})
const updatedCount = () => {count.value ++
}
</script>
2.5、绑定多个值
  • 父组件:
<template><div><ChildMy v-model:count="count" v-model:person="person" />{{ person }} - {{ count }}</div>
</template><script setup>
import ChildMy from './components/child.vue'
import { ref,reactive  } from 'vue'
const count = ref(1)
const person = reactive ({name: 'Lucy',age: 11})
</script>
  • 子组件:
<template><div>{{ person }} - {{ count }}<button @click="updatedData">child btn</button></div>
</template><script setup>
const person = defineModel("person")
const count = defineModel("count")const updatedData = () => {count.value ++person.value.age = 22person.value.name = "lilei"
}
</script>
2.6、修饰符和转换器

为了获取 v-model 指令使用的修饰符,我们可以像这样解构 defineModel() 的返回值:

const [modelValue, modelModifiers] = defineModel()

当存在修饰符时,我们可能需要在读取或将其同步回父组件时对其值进行转换。我们可以通过使用 get 和 set 转换器选项来实现这一点:

  • 父组件:
<template><div><ChildMy v-model.trim="message"/>{{ message }}</div>
</template><script setup>import ChildMy from './child.vue'import { ref } from 'vue' const message = ref(' hello ')
</script>
  • 子组件:
<template><div>{{ message }}<button @click="updatedMsg">child btn</button></div>
</template><script setup>
const [message, modelModifiers] = defineModel({set(value) {if (modelModifiers.trim) {value=value?.trim()}return value}
})const updatedMsg = () => {message.value += ` world`
}
</script>
2.7、修饰符串联
  • 父组件:
<template><div><ChildMy v-model.trim.lowercase="message"/>{{ message }}</div>
</template><script setup>import ChildMy from './child.vue'import { ref } from 'vue' const message = ref('Hello')
</script>
  • 子组件:
<template><div>{{ message }}<button @click="updatedMsg">child btn</button></div>
</template><script setup>
const [message, modelModifiers] = defineModel({get(value) {if (modelModifiers.trim) {value=value?.trim()}if (modelModifiers.lowercase) {value=value?.toLowerCase();}return value},set(value) {if (modelModifiers.trim) {value=value?.trim()}if (modelModifiers.lowercase) {value=value?.toLowerCase();}return value}
})const updatedMsg = () => {message.value += `World`
}
</script>
http://www.lryc.cn/news/407349.html

相关文章:

  • 耳机、音响UWB传输数据模组,飞睿智能低延迟、高速率超宽带uwb模块技术音频应用
  • webpack配置报错:Invalid options object.
  • Java 并发编程:一文了解 Java 内存模型(处理器优化、指令重排序与内存屏障的深层解析)
  • 谷粒商城实战笔记-64-商品服务-API-品牌管理-OSS前后联调测试上传
  • Springboot 开发之 RestTemplate 简介
  • Django transaction.atomic()事务处理
  • 2024.07-电视版免费影视App推荐和猫影视catvod、TVBox源(最新接口地址)
  • 【Python】 基于Q-learning 强化学习的贪吃蛇游戏(源码+论文)【独一无二】
  • 谷粒商城实战笔记-44-前端基础-Vue-整合ElementUI快速开发/设置模板代码
  • Android adb shell ps进程查找以及kill
  • [OJ]水位线问题,1.采用回溯法(深度优先遍历求解)2.采用广度优先遍历求解
  • 《华为数据之道》读书笔记六---面向自助消费的数据服务建设
  • go语言day18 reflect反射
  • 理解 Objective-C 中 `+load` 方法的执行顺序
  • C++:类和对象2
  • Docker安装kkFileView实现在线文件预览
  • ElasticSearch(四)— 数据检索与查询
  • Pytest之parametrize()实现数据驱动
  • 关于鸿蒙系统前景
  • 针对datax-web 中Swagger UI接口未授权访问
  • 生成式AI如何帮助小型企业高效运营?
  • 2024最新网络安全自学路线,内容涵盖3-5年技能提升
  • Postman API测试数据生成秘籍:技巧与实践
  • 【接口自动化_07课_Pytest+Excel+Allure完整框架集成_下】
  • Java开发之反射与动态代理
  • 实习日志1之大模型相关知识概览
  • 华为嵌入式面试题及参考答案(持续更新)
  • Java二十三种设计模式-装饰器模式(7/23)
  • 正则表达式与文本处理
  • Python | Leetcode Python题解之第283题移动零