Vue3 默认插槽和具名插槽的代码演示

49 min read

Vue3 使用默认插槽和具名插槽的代码演示如下:

默认插槽演示:

<!-- 父组件 -->
<template>
  <div>
    <h1>父组件</h1>
    <ChildComponent>
      <!-- 默认插槽 -->
      <p>这是默认插槽的内容</p>
    </ChildComponent>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent,
  },
}
</script>
<!-- 子组件 -->
<template>
  <div>
    <h2>子组件</h2>
    <!-- 默认插槽 -->
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
}
</script>

具名插槽演示:

<!-- 父组件 -->
<template>
  <div>
    <h1>父组件</h1>
    <ChildComponent>
      <!-- 具名插槽 -->
      <template #header>
        <h3>这是头部插槽的内容</h3>
      </template>
      <template #footer>
        <p>这是底部插槽的内容</p>
      </template>
    </ChildComponent>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent,
  },
}
</script>
<!-- 子组件 -->
<template>
  <div>
    <h2>子组件</h2>
    <!-- 具名插槽 -->
    <slot name="header"></slot>
    <!-- 默认插槽 -->
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
}
</script>

在上述代码中,父组件中的 ChildComponent 组件使用了默认插槽和具名插槽。默认插槽使用 <slot></slot>,而具名插槽使用 <slot name="插槽名称"></slot>,父组件通过在插槽中定义内容,把内容传递给子组件进行渲染。