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>

### 使用 `useSlots` 的方法 在 Vue 3 中,`useSlots` 是 Composition API 提供的一个函数,用于访问当前组件的插槽内容。这使得开发者可以在 `<script setup>` 或者普通的 Composition 函数中方便地操作响应插槽的变化。 #### 基本用法 通过引入 `useSlots` 并调用它来获取所有的插槽对象: ```javascript <script setup> import { useSlots } from &#39;vue&#39; const slots = useSlots() </script> ``` 一旦获得了 `slots` 对象,就可以像下面这样检查是否存在特定名称的插槽,并渲染不同的模板逻辑[^1]。 #### 实际应用例子 假设有一个父组件向子组件传递了一个具名插槽,默认情况下会显示一些文字;如果提供了该插槽,则展示来自父级的内容: ##### 子组件 (ChildComponent.vue) ```html <template> <div class="child-component"> <!-- 渲染默认内容 --> <slot name="header">Default Header Content</slot> <!-- 动态判断是否有提供 header 插槽并相应处理 --> {{ hasHeaderSlot ? "Custom Header Provided!" : "" }} <!-- 主体部分 --> <p>Main content area...</p> </div> </template> <script setup> import { computed, useSlots } from &#39;vue&#39; // 获取所有可用的 slot const slots = useSlots() // 计算属性检测是否含有名为 &#39;header&#39; 的插槽 const hasHeaderSlot = computed(() => !!slots.header) </script> ``` 在这个例子中,当父组件给定一个具有相同名字 (`header`) 的插槽时,页面上将会显示出 `"Custom Header Provided!"`; 否则就只会看到默认的文字说明.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值