vue2 详细介绍插槽使用

插槽可以帮助你构建灵活和可复用的组件,分别有基本插槽、具名插槽和作用域插槽。

1.基本使用: 

子组件:

<template>
  <div class="child">
    <h3>Child Component</h3>
    <slot></slot>   放置插槽的位置 
  </div>
</template>

父组件

    <child-component>
      <p>This is the content from the parent component.</p>
    </child-component>

2.具名插槽

子组件

<template>
  <div class="child">
    <h3>Child Component</h3>
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>

父组件

<template>
  <div class="parent">
    <h1>Parent Component</h1>
    <child-component>
      <template v-slot:header>
        <h2>This is the header content.</h2>
      </template>
      <template v-slot:default>
        <p>This is the default content.</p>
      </template>
      <template v-slot:footer>
        <p>This is the footer content.</p>
      </template>
    </child-component>
  </div>
</template>

3. 作用域插槽

    作用域插槽允许你将数据从子组件传递到插槽中,使得父组件可以使用这些数据。这对于需要在插槽中使用子组件数据的场景非常有用。

子组件

<template>
  <div>
      <h1>我是子组件</h1>
      <div>
        <h1 if="isshow===1">显示</h1>
        <h1 else>隐藏</h1>
      </div>
      <slot></slot>
      <!-- 具名插槽 -->
      <slot name="name"></slot>
         <slot :user="user"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isshow: 1,
      user: {
        name: 'John Doe',
        age: 25
      }
    }
  }
}
</script>

<style>

</style>

总结

  1. 基本插槽:用于简单的内容插入。
  2. 具名插槽:用于在子组件中定义多个插槽,父组件可以通过名字插入不同内容。
  3. 作用域插槽:用于将子组件的数据传递给插槽,父组件可以使用这些数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值