Vue Slot:介绍与使用示例

73 阅读1分钟

Vue 的插槽(slot)是一种特殊的模板语法,允许你定义组件模板中的“插槽”,然后在父组件中填充这些“插槽”。这样可以更灵活地组合组件。Vue 提供了几种不同类型的插槽:默认插槽、具名插槽和作用域插槽。下面我们将介绍这些插槽的使用方法,并提供一些示例代码。

默认插槽

介绍

默认插槽允许你在组件模板中定义一个位置,然后在父组件中插入任意内容。

示例代码

<!-- ChildComponent.vue -->
<template>
  <div>
    <slot>默认内容</slot>
  </div>
</template>

<!-- ParentComponent.vue -->
<template>
  <ChildComponent>
    <p>插入的内容</p>
  </ChildComponent>
</template>

具名插槽

介绍

具名插槽允许你定义多个插槽,并通过名字来区分它们。

示例代码

<!-- ChildComponent.vue -->
<template>
  <div>
    <header>
      <slot name="header">默认头部内容</slot>
    </header>
    <main>
      <slot>默认主体内容</slot>
    </main>
    <footer>
      <slot name="footer">默认底部内容</slot>
    </footer>
  </div>
</template>

<!-- ParentComponent.vue -->
<template>
  <ChildComponent>
    <template v-slot:header>
      <p>自定义头部内容</p>
    </template>
    <p>自定义主体内容</p>
    <template v-slot:footer>
      <p>自定义底部内容</p>
    </template>
  </ChildComponent>
</template>

作用域插槽

介绍

作用域插槽允许你访问子组件中的数据,然后在父组件中使用这些数据。

示例代码

<!-- ChildComponent.vue -->
<template>
  <ul>
    <slot v-bind:items="items">
      <li v-for="item in items" :key="item.id">{{ item.text }}</li>
    </slot>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, text: 'Item 1' },
        { id: 2, text: 'Item 2' },
      ],
    };
  },
};
</script>

<!-- ParentComponent.vue -->
<template>
  <ChildComponent>
    <template v-slot:default="slotProps">
      <li v-for="item in slotProps.items" :key="item.id">
        自定义内容:{{ item.text }}
      </li>
    </template>
  </ChildComponent>
</template>

通过这些示例,你可以看到 Vue 插槽提供了一种灵活和强大的方式来组合组件。希望这能帮到你!