Home > Web Front-end > JS Tutorial > A Comprehensive Guide to Vue Slots

A Comprehensive Guide to Vue Slots

Lisa Kudrow
Release: 2025-02-09 11:54:14
Original
368 people have browsed it

A Comprehensive Guide to Vue Slots

The core of modern web application development is components. Each application is composed of multiple components that work together to form a whole. To be reused in different scenarios and even in different applications, these components need to have the greatest flexibility and reusability. Many frameworks (Vue in particular) use a mechanism called "slots" to meet these needs.

Slots are a powerful and versatile content distribution and combination mechanism. You can think of slots as customizable templates (similar to PHP templates) that can be used in different locations and in various use cases, producing different effects. For example, in a UI framework like Vuetify, slots are used to create common components, such as alert components. In these components, slots serve as placeholders for default content and any additional/optional content (such as icons, images, etc.).

Slots allow you to add any structure, style, and functionality to specific components. By using slots, developers can significantly reduce the number of props used in a single component, making components simpler and easier to manage.

This tutorial will explore how to take advantage of slots in Vue 3. Let's get started.

Key Points

  • Vue slots enhance component flexibility: slots in Vue.js allow dynamic placement of content within the component, making it highly reusable and adapted to different contexts.
  • Basic slots and scope slots: Vue offers two types of slots—basic slots and scope slots. Basic slots are used for simple content replacement, while scope slots allow access to subcomponent data, enabling more complex and interactive content integration.
  • Multiple slots and named slots add structural complexity: For components that require multiple content areas, Vue supports multiple slots, including named slots, which helps to organize content more effectively and improve functionality Maintenance.
  • Slots vs. props: While props are critical to passing data to components, slots provide a more flexible solution for managing complex content structures and reducing dependencies on props for content distribution.
  • Practical application of slots: Vue slots are not limited to static content, but can also be used to deliver complete templates or interactive functions, thereby enhancing the functionality and interactivity of components.
  • Use slots with props for best component design: The best practice is to use slots for content management and props for data processing within components, which can make components more efficient and clearer.

Basic slot usage

Vue mainly offers two slots: simple slot and scope slot. Let's start with a simple slot. Consider the following example:

const app = Vue.createApp({})

app.component('primary-button', {
  template: `
    <button>
      <slot>OK</slot>
    </button>
  `
})

app.mount('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bapp')
Copy after login

Here, we have a main button component. We want the button text to be customizable, so we use the slot component inside the button element to add text placeholders. If we do not provide custom values, we also want a default (fallback) common value. Vue uses everything we put inside the slot component as the default slot content. So we just have to place the text "OK" inside the component. Now we can use the component like this:

<div id="app">
  <primary-button></primary-button>
</div>
Copy after login

The result is a button with text "OK" because we don't provide any value. But what if we want to create a button with custom text? In this case, we provide custom text in the component implementation as follows:

<div id="app">
  <primary-button>Subscribe</primary-button>
</div>
Copy after login

Here, Vue takes the custom text "Subscribe" and uses it instead of the default text.

As you can see, even in this simple example, we can gain a lot of flexibility in how to render components. But this is just the tip of the iceberg. Let's look at a more complex example.

Build a "Sentence of the Day" component

Now, we will build a component that displays a daily sentence. Here is the code:

const app = Vue.createApp({})

app.component('quote', {
  template: `
    <div>
      <h2>The quote of the day says:</h2>
      <p>
        <slot></slot>
      </p>
    </div>
  `
})

app.mount('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bapp')
Copy after login
<div id="app">
  <quote>
    <div class="quote-box">
      <span class="quote-text">"Creativity is just connecting things."</span>
      <br>
      - Steve Jobs
    </div>
  </quote>
</div>
Copy after login
.quote-box {
  background-color: lightgreen;
  width: 300px;
  padding: 5px 10px;
}

.quote-text {
  font-style: italic;
}
Copy after login

In this example, we create a title whose content will remain the same, and then we put the slot component in the paragraph whose content will change based on the quotes of the day. When rendering a component, Vue will display the title from the quote component, followed by the content we put inside the quote tag. Also pay attention to the CSS classes used in quote creation and implementation. We can style the component in two ways as needed.

Using multiple slots

While a single slot is very powerful, in many cases this is not enough. In real-life scenarios, we usually need multiple slots to get the job done. Fortunately, Vue allows us to use as many slots as we want. Let's see how to use multiple slots by building a simple card component.

Build basic card components

We will build a card component with three parts: title, body and footer:

const app = Vue.createApp({})

app.component('card', {
  template: `
    <div>
      <slot name="header"></slot>
      <main>
        <slot></slot>
      </main>
      <slot name="footer"></slot>
    </div>`
})

app.mount('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bapp')
Copy after login
<div id="app">
  <card>
    <template v-slot:header>
      <h2>Card Header Title</h2>
    </template>

    <template v-slot:default>
      <p>
        Lorem ipsum leo risus, porta ac consectetur ac, vestibulum at eros. Donec id elit non mi porta gravida at eget metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras mattis consectetur purus sit amet fermentum.
      </p>
    </template>

    <template v-slot:footer>
      <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b">Save</a> -
      <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b">Edit</a> -
      <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b">Delete</a>
    </template>
  </card>
</div>
Copy after login

In order to use multiple slots, we must provide a name for each slot. The only exception is the default slot. So, in the example above, we add a name attribute to the header and footer slots. Slots that do not provide names are considered as default slots.

When we use the card component, we need to use template element with the v-slot directive and slot name: v-slot:[slot-name].

(The remaining part is omitted here because the length is too long. Please selectively retain or delete some content as needed.)

The above is the detailed content of A Comprehensive Guide to Vue Slots. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template