vue3使用useAttrs和useSlots

举例: 比如当前使用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>

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值