具名 Slot
- 原理:具名 Slot 允许在组件模板中定义多个插槽,每个插槽有一个唯一的名字,通过这种方式可以在父组件中指定不同的内容片段插入到子组件的对应插槽位置。
- 代码实现:
- 子组件(假设为
ComplexComponent.vue
):
<template>
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
- **父组件**:
<template>
<ComplexComponent>
<template v-slot:header>
<h1>这是头部内容</h1>
</template>
<p>这是中间主要内容</p>
<template v-slot:footer>
<p>这是底部内容</p>
</template>
</ComplexComponent>
</template>
<script>
import ComplexComponent from './ComplexComponent.vue';
export default {
components: {
ComplexComponent
}
}
</script>
作用域 Slot
- 原理:作用域 Slot 允许子组件向父组件传递数据,父组件可以根据接收到的数据来决定如何渲染插槽内容。这样就可以在不同业务逻辑下,基于子组件传递的数据动态显示不同内容片段。
- 代码实现:
- 子组件(假设为
DynamicComponent.vue
):
<template>
<div>
<slot :data="componentData">
<!-- 插槽默认内容,当父组件没有提供作用域插槽时显示 -->
<p>默认内容:{{ componentData }}</p>
</slot>
</div>
</template>
<script>
export default {
data() {
return {
componentData: '子组件的数据'
}
}
}
</script>
- **父组件**:
<template>
<DynamicComponent>
<template v-slot:default="slotProps">
<div v-if="slotProps.data === '子组件的数据'">
<p>基于子组件数据显示的特定内容 1</p>
</div>
<div v-else>
<p>其他情况显示的内容</p>
</div>
</template>
</DynamicComponent>
</template>
<script>
import DynamicComponent from './DynamicComponent.vue';
export default {
components: {
DynamicComponent
}
}
</script>