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>
相关推荐
码界奇点3 分钟前
基于eBPF技术的高性能网络防火墙系统设计与实现
开发语言·网络·毕业设计·php·wpf·go语言·源代码管理
一起养小猫5 分钟前
Flutter for OpenHarmony 实战:ListView与GridView滚动列表完全指南
开发语言·javascript·flutter
程序员清洒6 分钟前
Flutter for OpenHarmony:ListView — 高效滚动列表
开发语言·flutter·华为·鸿蒙
naruto_lnq6 分钟前
C++与自动驾驶系统
开发语言·c++·算法
熊猫钓鱼>_>13 分钟前
从零到一:打造“抗造” Electron 录屏神器的故事
前端·javascript·ffmpeg·electron·node·录屏·record
wjs202415 分钟前
jEasyUI 启用行内编辑
开发语言
夕除16 分钟前
js--6
java·开发语言
ytttr87317 分钟前
C#实现海康威视智能车牌识别
开发语言·c#
梵刹古音22 分钟前
【C语言】 关键字与用户标识符
c语言·开发语言
悟能不能悟24 分钟前
grpc协议
开发语言