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

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

一、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 = 22
    person.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>
目录
打赏
0
0
0
0
14
分享
相关文章
基于 ant-design-vue 和 Vue 3 封装的功能强大的表格组件
VTable 是一个基于 ant-design-vue 和 Vue 3 的多功能表格组件,支持列自定义、排序、本地化存储、行选择等功能。它继承了 Ant-Design-Vue Table 的所有特性并加以扩展,提供开箱即用的高性能体验。示例包括基础表格、可选择表格和自定义列渲染等。
vue2和vue3的响应式原理有何不同?
大家好,我是V哥。本文详细对比了Vue 2与Vue 3的响应式原理:Vue 2基于`Object.defineProperty()`,适合小型项目但存在性能瓶颈;Vue 3采用`Proxy`,大幅优化初始化、更新性能及内存占用,更高效稳定。此外,我建议前端开发者关注鸿蒙趋势,2025年将是国产化替代关键期,推荐《鸿蒙 HarmonyOS 开发之路》卷1助你入行。老项目用Vue 2?不妨升级到Vue 3,提升用户体验!关注V哥爱编程,全栈开发轻松上手。
102 2
高效工作流:用Mermaid绘制你的专属流程图;如何在Vue3中导入mermaid绘制流程图
mermaid是一款非常优秀的基于 JavaScript 的图表绘制工具,可渲染 Markdown 启发的文本定义以动态创建和修改图表。非常适合新手学习或者做一些弱交互且自定义要求不高的图表 除了流程图以外,mermaid还支持序列图、类图、状态图、实体关系图等图表可供探索。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
vue父子组件及非父子组件通信
vue父子组件及非父子组件通信
168 0
vue父子组件及非父子组件通信
vue父子组件通信以及非父子组件通信的方法
vue父子组件通信以及非父子组件通信的方法
165 0
vue父子组件通信以及非父子组件通信的方法
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)
285 0
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)
总结Vue第二天:自定义子组件、父子组件通信、插槽
总结Vue第二天:自定义子组件、父子组件通信、插槽
228 0
总结Vue第二天:自定义子组件、父子组件通信、插槽
Vue 通过props实现父子组件通信
本文目录 1. 前言 2. 开发新闻列表父组件 3. 开发新闻内容子组件 4. 小结
150 0
Vue 父子组件间的通信
前言 在 Vue 项目中父子组件的通信是非常常见的,最近做项目的时候发现对这方面的知识还不怎么熟练,在这边做一下笔记,系统学习一下吧。
1050 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等