举例: 比如当前使用element的组件但是需要再次对element组件进行封装那么可以直接在父组件绑定v-bind, 然后在自组件对element组件绑定useAttrs实现props穿透
父组件:
<script setup lang="ts">
import Myavatar from '@/components/avatar/index.vue';
import MyCard from '@/components/card/index.vue';
</script>
<template>
<Myavatar
title="头像"
:size="100"
src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
></Myavatar>
<MyCard>
<template #header>
<div class="card-header">
<span>Card name</span>
<el-button class="button" text>Operation button</el-button>
</div>
</template>
<h2>哈哈哈哈哈哈</h2>
</MyCard>
</template>
子组件: 给el-avatar绑定上useAttrs, 这样就是父组件穿透孙子组件props, 这样的话父组件中就能直接绑定el-avatar的所有props属性
<script setup lang="ts">
import { useAttrs } from 'vue';
interface Props {
title: string;
}
const props = withDefaults(defineProps<Props>(), {
title: 'hello'
});
const attrs = useAttrs();
</script>
<template>
<div>
<h2>{{ props.title }}</h2>
<el-avatar v-bind="attrs" />
</div>
</template>
子组件:给el-card绑定slot,这样父组件定义的插槽就能直接渲染到子组件中的el-card相当于父组件的插槽直接渲染到孙子组件
<script setup lang="ts">
import { useSlots } from 'vue';
const slots = useSlots();
console.log(slots);
</script>
<template>
<el-card class="box-card">
<template v-for="(item, key, i) in slots" :key="i" v-slot:[key]>
<span>{{ key }}</span>
<slot :name="key"></slot>
</template>
</el-card>
</template>