How to use slots in vue

A slot in Vue is a special attribute of a component that is used to define a reusable template in the component so that content can be inserted into a specific position in the component. Slots can help us achieve reusable and configurable components.

In Vue, slots are <slot>represented by tags and can be used anywhere in a component's template that content needs to be inserted.

Here is a simple example showing how to use slots in components:

<template>
  <div>
    <h2>{
   
   { title }}</h2>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    title: String
  }
}
</script>

In this component, we define a slot and use <slot>the label. This slot can be filled anywhere in the component.

When using this component, we can add arbitrary HTML code inside the component tag, which will be filled into the slot:

<my-component title="My Title">
  <p>This is some content that will be placed inside the slot</p>
</my-component>

In this example, <p>the content in the element will be filled into the component's slot.

In addition to the default slots, Vue also supports named slots, which can be defined using attributes <slot>of tags nameand v-slotprovided with content using directives. Named slots can help us have more fine-grained control over a component's template.

For example, here's a component with named slots:

<template>
  <div>
    <h2>{
   
   { title }}</h2>
    <slot name="content"></slot>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    title: String
  }
}
</script>

In this component, we define two named slots, one called contentand one called footer. We can use v-slotdirectives to provide content to these slots:

<my-component title="My Title">
  <template v-slot:content>
    <p>This is some content that will be placed inside the content slot</p>
  </template>
  <template v-slot:footer>
    <p>This is some content that will be placed inside the footer slot</p>
  </template>
</my-component>

In this example, <template>the content in the element will be filled into the corresponding named slot.

Guess you like

Origin blog.csdn.net/zhangkunsir/article/details/130175537