vue3 插槽使用方法

vue3 插槽使用方法

让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件

包含:默认插槽、具名插槽、作用域插槽、具名作用域插槽

默认插槽

没有名字的插槽,只有一个slot Category标签的内容会替代slot标签

App.vue

  <Category>
       <div>html结构1</div>
       <div>html结构2</div>
      
      // 通过具名插槽的方式填写
      <template #default>
        <p>A paragraph for the main content.</p>
        <p>And another one.</p>
      </template>
      
  </Category>

Category.vue

<template>
  <div>
     <!-- 定义插槽 -->
     <slot>插槽默认内容...</slot>
  </div>
</template>

具名插槽

1、在可以在子组件中用多个插槽,子组件用 name,

2、父组件填写方式一:slot="list"

3、方式二:v-slot:list 或者简写为 #list

父组件

<Category title="foods">
    // 多个标签
    <template slot="list">
        <h1>111</h1>
        <h1>222</h1>
    </template>
    <template v-slot:l>
        <h1>111</h1>
        <h1>222</h1>
    </template>    
    <template #list>
        <h1>111</h1>
        <h1>222</h1>
    </template>
    
    // 单标签
    <a href="#" slot="ad" >我是广告</a>
</Category>

子组件 Category.vue

<template>
    <div class="category">
        具名插槽
        <slot name="list">列表</slot>
        
        <slot name="ad">广告</slot>    
    </div>  
</template>

父组件还可以用用动态插槽名:

<base-layout>
  <template v-slot:[slotName]>
    ...
  </template>

  <!-- 缩写为 -->
  <template #[slotName]>
    ...
  </template>
</base-layout>

<script setup>
let slotName = ref('demo')
</script>

作用域插槽

可以通过插槽完成组件通信,特别是传递 DOM 元素的时候

父组件插槽中可以接收子组件的参数(默认插槽)

<!-- <MyComponent> 子组件(默认插槽) -->
<div>
  <slot :text="greetingMessage" :count="1"></slot>
</div>
<!-- 父组件(默认插槽) -->
<MyComponent v-slot="slotProps">
  {{ slotProps.text }} {{ slotProps.count }}
</MyComponent>

<!-- 还可以解构 -->
<MyComponent v-slot="{ text, count }">
  {{ text }} {{ count }}
</MyComponent>

具名插槽写法

<!-- <MyComponent> 子组件(具名插槽) -->
<slot name="header" message="header"></slot>
<slot name="footer" message="footer"></slot>
<slot message="defalut"></slot>
<MyComponent>
  <template #header="headerProps">
    {{ headerProps }}
    {{ headerProps.message }}
  </template>

  <template #default="defaultProps">
    {{ defaultProps }}
  </template>

  <template #footer="footerProps">
    {{ footerProps }}
  </template>
</MyComponent>

v-slot:name="slotProps" 简写为 #name="slotProps"

useSlots

import { useSlots } from 'vue'

// 获取插槽内容
let slots = useSlots()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cocoonne

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值