Vue中的slot插槽

插槽-----在父组件中往子组件中指定位置插入html结构。

1.插槽是什么

Vue 插槽是一种非常强大的功能,允许开发者在父组件中定义模板的一部分,然后在子组件中指定这部分模板的具体内容。这在创建可复用组件时非常有用,因为它允许组件的使用者决定组件的某些部分应该如何渲染。

2.默认插槽

默认插槽是最简单的插槽类型,你可以在子组件中定义一个元素,父组件可以在此处插入自己的内容。

子组件:

<template>
  <div class="child-component">
    <slot>这是默认内容</slot>
  </div>
</template>

父组件:

<template>
  <div class="parent-component">
    <ChildComponent>
      <p>这是插入的内容</p>
    </ChildComponent>
  </div>
</template>
 
<script>
import ChildComponent from './ChildComponent.vue';
 
export default {
  components: {
    ChildComponent
  }
}
</script>

3.具名插槽

具名插槽允许你为插槽命名,这样可以在同一个组件中定义多个插槽,并且在父组件中指定具体使用哪个插槽。
子组件:

<template>
  <div class="child-component">
    <slot name="header">默认头部内容</slot>
    <slot>默认内容</slot>
    <slot name="footer">默认底部内容</slot>
  </div>
</template>

父组件:

<template>
  <div class="parent-component">
    <ChildComponent>
      <template v-slot:header>
        <h1>自定义头部</h1>
      </template>
      <p>自定义内容</p>
      <template v-slot:footer>
        <p>自定义底部</p>
      </template>
    </ChildComponent>
  </div>
</template>

或者使用简写方式:

<ChildComponent>
  <template #header>
    <h1>自定义头部</h1>
  </template>
  <p>自定义内容</p>
  <template #footer>
    <p>自定义底部</p>
  </template>
</ChildComponent>

4.作用域插槽

作用域插槽允许子组件的数据传递到父组件的插槽内容中。这通常通过在<slot>元素上使用v-bindv-slot的属性来实现。
子组件:

<template>
  <div class="child-component">
    <slot name="item" v-for="item in items" :item="item" :key="item.id">
      {{ item.text }} <!-- 默认内容 -->
    </slot>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      items: [{ id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }]
    }
  }
}
</script>

父组件:

<template>
  <div class="parent-component">
    <ChildComponent>
      <template v-slot:item="slotProps"> <!-- 使用 v-slot 接收数据 -->
        <span>{{ slotProps.item.text }} (Scoped)</span> <!-- 使用数据 -->
      </template>
    </ChildComponent>
  </div>
</template>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值