了解 vue插槽 Slots

在 Vue.js 中,插槽(Slots)是一种非常强大的功能,允许你在组件中插入动态内容,从而使组件变得更灵活和可重用。

一、默认内容

允许将父组件的内容传递到子组件中。这使得子组件能够显示父组件传递的内容,并且可以灵活地调整和嵌套内容。(有点像props)

//父组件
<template>
  <my-component>
    <p>这是向子组件传的值</p>
  </my-component>
</template>

//子组件 
<template>
  <div>
    <slot></slot>
  </div>
</template>

二、具名插槽

允许在子组件中定义多个插槽,并给它们分配不同的名称。父组件可以通过插槽的名称来插入特定的内容。

//子组件
<template>
  <div>
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

//父组件
<template>
  <my-component>
    <template v-slot:header>  //也可以写为#header
      <h1>`Header Content`</h1>
    </template>
    <template v-slot:default>  //default
      <p>`Main Content`</p>
    </template>
    <template v-slot:footer> //#footer
      <p>`Footer Content`</p>
    </template>
  </my-component>
</template>

三、条件插槽

这个用的少,忽略…

四、动态插槽

允许在插槽中动态选择组件进行渲染。这对于需要根据条件渲染不同内容的场景非常有用。

//子组件
<template>
  <component :is="currentComponent"></component>
</template>

<script>
export default {
  props: ['currentComponent']
}
</script>

//父组件
<template>
  <my-component :currentComponent="componentToRender"></my-component>
</template>

<script setup>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

const componentToRender = ref(null)
componentToRender.value = ComponentA 

</script>

五、作用域插槽

允许父组件获取子组件的数据并利用这些数据进行自定义渲染。这在需要将子组件内部的数据传递到父组件时非常有用。(有点像emit)

//子组件
<template>
  <div>
    <slot :data="data" :text="text"></slot>
  </div>
</template>

<script setup>
  const data = ref('这是向父组件传递的值') 
  const text = ref('111')
}
</script>

//父组件
<template>
  <my-component v-slot="slotProps">
    <p>{{ slotProps.data }} {{ slotProps.text}}</p> 
  </my-component>
</template>
也可以解构
<template>
  <my-component v-slot="{data, text}">
    <p>{{ slotProps.data }} {{ slotProps.text}}</p> 
  </my-component>
</template>

总结

插槽的作用:

  1. 将父组件内容插入子组件。
  2. 使用具名插槽在子组件中定义多个插槽位置。
  3. 实现动态组件插槽,动态渲染不同组件。
  4. 利用作用域插槽将子组件的数据传递到父组件。
    参考官网:插槽
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jet_closer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值