返回

Vue组件封装神器:slot插槽

前端

slot插槽基础用法

slot最基本的使用方法是将子组件的内容插入到父组件的特定位置。在父组件中,你可以在需要插入子组件的地方使用<slot>标签,而在子组件中,你可以在需要被插入到父组件中的内容上使用<template>标签。

例如,以下代码展示了如何在父组件中使用<slot>标签插入子组件的内容:

<template>
  <div>
    <slot></slot>
  </div>
</template>

以下代码展示了如何在子组件中使用<template>标签将内容插入到父组件中:

<template>
  <div>
    <h1>子组件的内容</h1>
  </div>
</template>

当你在父组件中使用<slot>标签时,子组件的内容将会被插入到<slot>标签的位置。

slot插槽高级用法

除了基本用法之外,slot还有很多高级用法。这些高级用法可以让你创建出更加灵活和可重用的组件。

具名插槽

具名插槽允许你指定子组件的内容应该插入到父组件的哪个位置。在父组件中,你可以在<slot>标签上使用name属性来指定插槽的名称。而在子组件中,你可以在<template>标签上使用slot属性来指定该模板应该被插入到父组件中哪个具名插槽中。

例如,以下代码展示了如何在父组件中使用具名插槽:

<template>
  <div>
    <slot name="header"></slot>
    <slot name="content"></slot>
    <slot name="footer"></slot>
  </div>
</template>

以下代码展示了如何在子组件中使用具名插槽:

<template>
  <div>
    <template slot="header">
      <h1>子组件的头部内容</h1>
    </template>
    <template slot="content">
      <p>子组件的主体内容</p>
    </template>
    <template slot="footer">
      <small>子组件的尾部内容</small>
    </template>
  </div>
</template>

当你在父组件中使用具名插槽时,子组件的内容将会被插入到父组件中具有相同名称的<slot>标签的位置。

作用域插槽

作用域插槽允许你将父组件的数据传递给子组件。在父组件中,你可以在<slot>标签上使用v-bind指令来将数据传递给子组件。而在子组件中,你可以在<template>标签上使用v-slot指令来接收父组件传递过来的数据。

例如,以下代码展示了如何在父组件中使用作用域插槽:

<template>
  <div>
    <slot :message="message"></slot>
  </div>
</template>

以下代码展示了如何在子组件中使用作用域插槽:

<template>
  <div>
    <template v-slot:default="slotProps">
      <h1>{{ slotProps.message }}</h1>
    </template>
  </div>
</template>

当你在父组件中使用作用域插槽时,父组件的数据将会被传递给子组件。子组件可以通过v-slot指令来接收这些数据。

插槽事件

插槽事件允许你在子组件中触发父组件的方法。在父组件中,你可以在<slot>标签上使用@符号来监听子组件触发的事件。而在子组件中,你可以在<template>标签上使用v-on指令来触发父组件的方法。

例如,以下代码展示了如何在父组件中监听子组件触发的事件:

<template>
  <div>
    <slot @click="handleClick"></slot>
  </div>
</template>

以下代码展示了如何在子组件中触发父组件的方法:

<template>
  <div>
    <template v-slot:default>
      <button @click="$emit('click')">点击我</button>
    </template>
  </div>
</template>

当你在子组件中触发事件时,父组件将会收到该事件并执行相应的方法。

slot插槽常见使用场景

slot插槽在Vue开发中有很多常见的