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

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

1. props

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

子组件childComponent:

<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>

父组件:

<ChildComponent msg="Hello" :count="5" />

 2. Emits

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

子组件:

<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>

父组件:

<ChildComponent @updateCount="handleUpdateCount" />

3. Slots

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

子组件:

<template>  
  <div>  
    <slot name="header"></slot>  
    <slot></slot>  
  </div>  
</template>

父组件:

<ChildComponent>  
  <template #header>  
    <h1>This is the header</h1>  
  </template>  
  <p>This is the default slot content.</p>  
</ChildComponent>

4. Provide / Inject

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

祖先组件:

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

子组件:

<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 函数来获取。

<script setup lang="ts">  
import { useContext } from 'vue'  
  
const { attrs, slots, emit } = useContext()  
</script>

  • 19
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值