search
HomeWeb Front-endJS TutorialUnderstanding Slots in Vue ith Composition API

Understanding Slots in Vue ith Composition API

Slots are a powerful mechanism in Vue that enable components to define content areas that can be customized by the parent component. This promotes reusability and flexibility in building UI components. Vue 3 offers two primary slot types:

  • Normal Slots: Provide a simple way to inject content from the parent component into the child component's template.
  • Scoped Slots: Allow for more advanced customization by passing data (a scope) from the child component to the slot content, enabling dynamic rendering based on both parent and child data.

In Vue 3, slots allow you to create flexible components by providing a way to pass content into child components. The Composition API enhances how we use slots, making it more intuitive and powerful.

What are Slots?

Slots are a way to define placeholder content in a component that can be filled with custom content when the component is used. They help in creating reusable and customizable components.

Types of Slots

  • Default Slot: The most common type, it allows you to pass content without any specific name.
  • Named Slots: These allow you to specify different slots with unique names, enabling more complex layouts.
  • Scoped Slots: These provide a way to expose data from the child component to the parent component using a slot. Using Slots with the Composition API

Using Slots with the Composition API

Here’s how you can define and use slots in a Vue 3 component using the Composition API:
Example of a Default Slot

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

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'MyComponent',
});
</script>

Usage:

<mycomponent>
  <p>This is some content passed to the default slot!</p>
</mycomponent>


Named Slots

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

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'LayoutComponent',
});
</script>


Usage:

<layoutcomponent>
  <template>
    <h1 id="Header-Content">Header Content</h1>
  </template>

  <p>Main Content goes here!</p>

  <template>
    <footer>Footer Content</footer>
  </template>
</layoutcomponent>


Scoped Slots

Scoped slots allow you to pass data from the child component back to the parent.

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

<script>
import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'MessageComponent',
  setup() {
    const message = ref("Hello from the child!");

    return { message };
  },
});
</script>

Usage:

<messagecomponent>
  <template message>
    <p>{{ message }}</p>
  </template>
</messagecomponent>

Example: Food Products Delivery with Slots in Vue 3

Let's create a simple food delivery application using Vue 3 with the Composition API and slots. This example will showcase a main FoodDelivery component that uses slots to display a list of food items, along with a header and footer.

Step 1: Create the Main Component

Here’s the FoodDeliverycomponent that accepts named slots for the header, food items, and footer.

<template>
  <div class="food-delivery">
    <slot name="header"></slot>
    <div class="food-items">
      <slot></slot>
    </div>
    <slot name="footer"></slot>
  </div>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'FoodDelivery',
});
</script>

<style>
.food-delivery {
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 8px;
}

.food-items {
  margin: 20px 0;
}
</style>

Step 2: Create Food Item Component

Next, let’s create a simple FoodItem component to represent individual food products.

<template>
  <div class="food-item">
    <h3 id="name">{{ name }}</h3>
    <p>Price: ${{ price.toFixed(2) }}</p>
    <button>Add to Cart</button>
  </div>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'FoodItem',
  props: {
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
  },
  methods: {
    addToCart() {
      // Logic to add the item to the cart
      console.log(`${this.name} added to cart!`);
    },
  },
});
</script>

<style>
.food-item {
  border: 1px solid #eee;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}
</style>


Step 3: Using the Components

Now, let’s put everything together in a parent component that uses our FoodDelivery and FoodItem components.

Let me Explain

FoodDelivery Component: This component acts as a layout for our food delivery service. It accepts three slots: a header, a default slot for the food items, and a footer.
FoodItem Component: This represents individual food products. It takes name and price as props and has a method to simulate adding the item to a cart.

  • App Component: This is the parent component where everything is brought together. It uses the FoodDelivery component and fills the slots with a welcome message, a list of FoodItemcomponents, and a thank you message.

Use Cases

  • Customizing Lists: Scoped slots are ideal for creating list components where each item can have distinct rendering logic based on its properties. The child component can pass the item data to the slot, and the parent component can define the template for each item using the scoped slot. (BasePaginated.vue)
  • Conditional Rendering: Scoped slots enable selective rendering within the child component based on data it provides to the slot. For instance, you could conditionally display a message or error state within the slot content.
  • Complex Layouts: Scoped slots facilitate the creation of more intricate layouts where different parts of the layout can be customized by the parent component while allowing the child component to inject specific content or functionality using the scope.
<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'MyComponent',
});
</script>

<mycomponent>
  <p>This is some content passed to the default slot!</p>
</mycomponent>


Advanced Considerations

  • Named Scoped Slots: You can assign names to scoped slots (e.g., ...), enabling you to have multiple scoped slots within a single child component and reference them by name in the parent component.
  • Slot Functions: In Vue 2, slots were accessed as $slotswithin the child component. Vue 3 offers a more reactive approach using $scopedSlots, which are functions that provide access to the slot content. This allows for dynamic slot manipulation and conditional rendering within the child component.

Let's enhance the scoped slot example to make it clearer and more functional. This example will demonstrate how to use scoped slots to pass item data from a child component to a parent component, allowing for flexible rendering.

Step 1: Create the ItemList Component

This component will display a list of items and use a scoped slot to allow the parent to customize how each item is rendered.

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

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'LayoutComponent',
});
</script>


Step 2: Using the ItemList Component with Scoped Slots

Now, let’s create a parent component that uses the ItemList component and provides a custom template for rendering each item using the scoped slot.

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

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'MyComponent',
});
</script>

ItemList Component:

  • This component defines a list of items and uses a scoped slot to expose each item to the parent component.
  • If no slot is provided, it defaults to displaying the item's description. ###Parent Component:
  • This component uses the ItemList and provides a custom template for rendering each item.
  • It accesses the item data through the scoped slot and includes a button that triggers a function when clicked.

The example demonstrates how to effectively use scoped slots in Vue 3 to create a flexible and reusable component structure. The parent component can customize the rendering of each item while still accessing the data provided by the child component.

Let's recap

This example illustrates how you can utilize slots in a Vue 3 application to create a flexible food delivery component system. You can easily customize the header, footer, and content without modifying the main component. If you have any further questions or need more details, feel free to ask in a comment.

By effectively leveraging normal and scoped slots in Vue 3 with the Composition API, you can build highly reusable and customizable UI components, promoting maintainability and code organization in your Vue applications. You can choose the appropriate slot type based on your specific content injection and dynamic rendering requirements.
The way to grow is to connect.
Happy coding!

The above is the detailed content of Understanding Slots in Vue ith Composition API. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools