第 4 章. 组件之间的相互作用
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
在第 3 章中,我们深入探讨了如何使用生命周期钩子、计算属性、观察者、方法和其他功能来组成一个组件。我们还了解了插槽的强大功能,以及如何使用道具从其他组件接收外部数据。
在此基础上,本章将指导你如何使用自定义事件和提供/注入模式建立组件之间的交互。本章还介绍了 Teleport API,它允许你在 DOM 树中移动元素,同时保持元素在 Vue 组件中的显示顺序。
Vue 中的嵌套组件和数据流
Vue 组件可以嵌套其他 Vue 组件。在复杂的用户界面项目中,这一功能非常方便用户将代码组织成更小、可管理和可重复使用的片段。我们将嵌套元素称为子组件,将包含子组件的组件称为父组件 。
Vue 应用程序中的数据流默认是单向的,这意味着父组件可以向子组件传递数据,但不能反向传递。父组件可以使用props 将数据传递给子组件(在"探索选项 API "中进行了简要讨论),而子组件可以使用自定义事件emits 将事件发送回父组件。图 4-1展示了组件之间的数据流 。
图 4-1. Vue 组件中的单向数据流
使用道具将数据传递给子组件
以对象或数组的形式,Vue 组件的props 字段包含该组件可从其父组件接收的所有可用数据属性。props 的每个属性都是目标组件的道具。要开始从父组件接收数据,需要在组件的选项对象中声明props 字段,如例 4-1 所示。
例 4-1. 在组件中定义道具
exportdefault{name:'ChildComponent',props:{name:String}}
在例 4-1 中,ChildComponent 组件接受一个类型为String 的name prop。然后,父组件可以使用该name prop 将数据传递给子组件,如例 4-2 所示。
例 4-2. 将静态数据作为道具传递给子组件
<template><ChildComponentname="Red Sweater"/></template><scriptlang="ts">importChildComponentfrom'./ChildComponent.vue'exportdefault{name:'ParentComponent',components:{ChildComponent},}</script>
在上一示例中,ChildComponent 接收静态的 "红色毛衣 "作为name 值。如果要向name 传递并绑定一个动态数据变量,如children 列表中的第一个元素,可以使用v-bind 属性(用: 表示),如例 4-3 所示。
例 4-3. 将动态变量作为道具传递给子组件
<template><ChildComponent:name="children[0]"/></template><scriptlang="ts">import
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access