在 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>
总结
插槽的作用:
- 将父组件内容插入子组件。
- 使用具名插槽在子组件中定义多个插槽位置。
- …
- 实现动态组件插槽,动态渲染不同组件。
- 利用作用域插槽将子组件的数据传递到父组件。
参考官网:插槽