插槽

插槽就是子组件中的提供给父组件使用的一个占位符,用 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的标签。

匿名插槽

vue
12345678910
<!-- 我是子组件slot_test.vue -->
<template>
  <div style="background-color: aqua; width: 1000px; height: 100px"></div>
  <div style="background-color: red; width: 1000px; height: 100px">
    <slot></slot>
  </div>
  <div
    style="background-color: greenyellow; width: 1000px; height: 100px"
  ></div>
</template>
vue
123456789
<!-- 父组件 -->
<template>
  <slot_test>
    <template #default>
      <h3>我是默认插槽</h3>
    </template>
  </slot_test>
</template>

具名插槽

vue
12345678910111213
<!-- 我是子组件slot_test.vue -->
<template>
  <div style="background-color: aqua; width: 1000px; height: 100px">
    <slot name="header"></slot>
  </div>
  <div style="background-color: red; width: 1000px; height: 100px">
    <slot></slot>
  </div>
  <div style="background-color: greenyellow; width: 1000px; height: 100px">
    <slot name="footer"></slot>
  </div>
</template>

vue
12345678910111213141516
<!-- 父组件 -->
<template>
  <slot_test>
    <template #default>
      <h3>我是默认插槽</h3>
    </template>
    <!-- 完整写法 -->
    <template v-slot:header>
      <h3>我是header插槽</h3>
    </template>
    <!-- 简写写法 -->
    <template #footer>
      <h3>我是footer插槽</h3>
    </template>
  </slot_test>
</template>

35ecac4d360a8843add693ca42e29448.png