学习优先度:★★★★☆

难易度:★★★☆☆

Vue.js 中的槽允许您将父组件中的内容分配到子组件模板中的特定位置。

下面是一个在 Vue.js 中使用槽的简单示例:

【代码示例】

<!-- Parent component -->
<template>
  <div>
  <h2>Parent Component</h2>
  <ChildComponent>
   <template v-slot:header>
​    <h3>This is the header content</h3>
   </template>
   <template v-slot:default>
        <p>This is the default content</p>
   </template>
   <template v-slot:footer>
        <p>This is the footer content</p>
   </template>
  </ChildComponent>
 </div>
</template>
<!-- Child component -->
<template>
  <div>
  <header>
   <slot name="header"></slot>
  </header>
  <main>
   <slot></slot>
  </main>
  <footer>
   <slot name="footer"></slot>
  </footer>
 </div>
</template>

【执行结果】

The result would be a rendered component with the header, default content, and footer distributed to their respective slots in the child component.

Vue.js 中的插槽为创建灵活、可重用的组件提供了一种强大的方法。父组件可以使用命名槽将内容传递到子组件的特定区域。父组件中使用 v-slot 指令(简写为 #)来指定内容应进入哪个槽。子组件则使用 <slot> 元素定义这些槽的位置。

在上面的示例中,我们有三个插槽:

一个命名为 “页眉 ”的插槽

一个默认插槽(没有名称)

一个已命名的 “页脚 ”槽

子组件可以为任何槽提供默认内容,如果父组件没有为该槽提供内容,则将使用默认内容。这使得组件更加灵活和可重复使用。

【补充】

Vue 3 引入了新的 v-slot 语法,取代了旧的 slot 和 slot-scope 属性。

您可以在模板中使用速记语法 # 代替 v-slot:。

通过作用域槽,您可以将子组件的数据传递回父组件,从而实现更强大的组件组合。