返回

Vue插槽教程:在组件之间传递内容、数据和组件

前端

slot>指定的位置)。

<template>
  <div>
    <slot></slot>
  </div>
</template>
<MyComponent>
  <h1>Hello, world!</h1>
  <p>This is a paragraph.</p>
</MyComponent>

以上示例中,MyComponent组件的模板中有一个<slot>元素,该元素表示在组件内部指定的位置插入内容。当使用<MyComponent>组件时,组件标签内的内容(<h1><p>元素)将自动填坑,替换组件模板中<slot>元素指定的位置。

slot插槽还可以传递数据。通过在<slot>元素上使用name属性,可以指定插槽的名称。然后,在组件标签内使用<slot>元素,并在其上使用name属性指定插槽的名称,即可向插槽传递数据。

<template>
  <div>
    <slot name="header"></slot>
    <slot name="content"></slot>
    <slot name="footer"></slot>
  </div>
</template>
<MyComponent>
  <template slot="header">
    <h1>Hello, world!</h1>
  </template>
  <template slot="content">
    <p>This is a paragraph.</p>
  </template>
  <template slot="footer">
    <p>Copyright 2023.</p>
  </template>
</MyComponent>

以上示例中,MyComponent组件的模板中有三个<slot>元素,分别用于插入头部、内容和尾部内容。当使用<MyComponent>组件时,组件标签内的内容将根据<slot>元素的name属性自动填坑,替换组件模板中<slot>元素指定的位置。

slot插槽还可以传递组件。通过在<slot>元素上使用component属性,可以指定要插入的组件。然后,在组件标签内使用<slot>元素,并在其上使用component属性指定要插入的组件,即可向插槽传递组件。

<template>
  <div>
    <slot name="header"></slot>
    <slot name="content"></slot>
    <slot name="footer"></slot>
  </div>
</template>
<MyComponent>
  <template slot="header">
    <HeaderComponent></HeaderComponent>
  </template>
  <template slot="content">
    <ContentComponent></ContentComponent>
  </template>
  <template slot="footer">
    <FooterComponent></FooterComponent>
  </template>
</MyComponent>

以上示例中,MyComponent组件的模板中有三个<slot>元素,分别用于插入头部、内容和尾部组件。当使用<MyComponent>组件时,组件标签内的内容将根据<slot>元素的component属性自动填坑,替换组件模板中<slot>元素指定的位置。

slot插槽是Vue.js中一种非常灵活的机制,它可以用于在组件之间传递内容、数据和组件。通过slot插槽,我们可以轻松地构建可重用的组件,并使组件之间的通信更加方便。