Skip to content
On this page

slot 插槽

在ts中编写组件,经常会涉及到插槽的一些操作。

getSlot 获取插槽并动态传递参数

ts
<template>
    <div>
        <slot name="test"></slot>
    </div>
</template>

<script lang="ts" setup>
    import { useSlots } from 'vue'

    // 获取所有插槽
    const slots = useSlots()
    // 动态标题
    const title = ref('我是一个动态标题')

    /**
     * @description 向test插槽传递一个动态的数据数据
     * @param slots 所有插槽
     * @param str 向哪个插槽传递数据
     * @param param 动态参数
    */
    getSlot(slots, 'test', title)

</script>

extendSlots 拷贝插槽

ts
/**
 * @param slots 所有插槽
 * @param excludeKeys 需要拷贝的插槽名称
*/
extendSlots(slots: Slots, excludeKeys?: string[])

getParentSlots 跨组件获取slot

包含两种用法:

1、 通过父组件的name获取

2、通过class名称获取

ts
/**
 * @param rootComponentName 父组件名称
 * @param string 在哪个class中获取插槽
*/
getParentSlots(rootComponentName?: string, cls?: string)

// 使用
// 通过父组件的name获取
getParentSlots('DtTheme')

// 通过class名称获取
getParentSlots(null, 'test')