vue3从精通到入门13:组件的传参方式

组件传参主要通过 props、emits、slots、provide/inject 以及 setup 函数中的 context 来实现。当使用 <script setup> 语法时,传参方式会更加简洁和直观。

1. props

props 是父组件向子组件传递数据的主要方式。我们可以使用 defineProps 函数来声明 props。

子组件childComponent:

html 复制代码
<script setup lang="ts">  
import { defineProps } from 'vue'  
  
const props = defineProps({  
  msg: String,  
  count: {  
    type: Number,  
    default: 0  
  }  
})  
</script>  
  
<template>  
  <div>{{ msg }} (Count: {{ count }})</div>  
</template>

父组件:

html 复制代码
<ChildComponent msg="Hello" :count="5" />

2. Emits

Emits 用于子组件向父组件发送消息或触发事件。可以使用 defineEmits 函数来声明可触发的事件。

子组件:

html 复制代码
<script setup lang="ts">  
import { defineEmits } from 'vue'  
  
const emit = defineEmits(['updateCount'])  
  
function increment() {  
  emit('updateCount', count + 1)  
}  
</script>  
  
<template>  
  <button @click="increment">Increment</button>  
</template>

父组件:

html 复制代码
<ChildComponent @updateCount="handleUpdateCount" />

3. Slots

Slots 允许你在父组件中向子组件的模板中插入内容。

子组件:

html 复制代码
<template>  
  <div>  
    <slot name="header"></slot>  
    <slot></slot>  
  </div>  
</template>

父组件:

html 复制代码
<ChildComponent>  
  <template #header>  
    <h1>This is the header</h1>  
  </template>  
  <p>This is the default slot content.</p>  
</ChildComponent>

4. Provide / Inject

Provide 和 Inject 允许祖先组件向其所有子孙组件提供一个依赖,而不论组件层次有多深。

祖先组件:

html 复制代码
<script setup lang="ts">  
import { provide } from 'vue'  
  
provide('themeColor', 'blue')  
</script>

子组件:

html 复制代码
<script setup lang="ts">  
import { inject } from 'vue'  
  
const themeColor = inject('themeColor', 'defaultColor')  
</script>

5. Context

<script setup> 中,你通常不需要直接访问 setup 函数的 context 参数,因为大部分功能(如 attrs、slots、emit 等)都已被直接暴露为顶层的绑定。但如果你确实需要访问完整的 context,你可以通过 useContext 函数来获取。

html 复制代码
<script setup lang="ts">  
import { useContext } from 'vue'  
  
const { attrs, slots, emit } = useContext()  
</script>
相关推荐
编程版小新1 分钟前
C++初阶:STL详解(四)——vector迭代器失效问题
开发语言·c++·迭代器·vector·迭代器失效
小白小白从不日白11 分钟前
react 组件通讯
前端·react.js
c4fx21 分钟前
Delphi5利用DLL实现窗体的重用
开发语言·delphi·dll
罗_三金21 分钟前
前端框架对比和选择?
javascript·前端框架·vue·react·angular
Redstone Monstrosity28 分钟前
字节二面
前端·面试
东方翱翔35 分钟前
CSS的三种基本选择器
前端·css
鸽芷咕44 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
Jhxbdks1 小时前
C语言中的一些小知识(二)
c语言·开发语言·笔记
java6666688881 小时前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存1 小时前
源码分析:LinkedList
java·开发语言