MST

星途 面试题库

面试题:Svelte中具名Slot与作用域Slot的应用

假设你正在开发一个复杂的组件库,其中某个组件需要根据不同的业务逻辑显示不同的内容片段。请详细阐述如何使用具名Slot和作用域Slot来实现这一需求,并给出具体的代码实现。
27.8万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

具名 Slot

  1. 原理:具名 Slot 允许在组件模板中定义多个插槽,每个插槽有一个唯一的名字,通过这种方式可以在父组件中指定不同的内容片段插入到子组件的对应插槽位置。
  2. 代码实现
    • 子组件(假设为 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

  1. 原理:作用域 Slot 允许子组件向父组件传递数据,父组件可以根据接收到的数据来决定如何渲染插槽内容。这样就可以在不同业务逻辑下,基于子组件传递的数据动态显示不同内容片段。
  2. 代码实现
    • 子组件(假设为 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>