Adding a component to a slot in Vue.js 3

My Goal

I aim to pass the Component into the designated slot.

The Inquiry

How can I effectively pass the Component into the slot for proper rendering? It works well with strings or plain HTML inputs.

Additional Query

If direct passing is not feasible, what other approach could be used to pass a component into another component following the structure below?

Parent Component

Template Code

<template>
  <card-with-title card-title="Title">
    <template #card-body>
      <row-fontawesome-icon-with-text v-for="mailDto in lastProcessedEmails"/>
    </template>
  </card-with-title>
</template>

Script Code - Key Sections

<script>
import SymfonyRoutes                     from '../../../../../core/symfony/SymfonyRoutes';
import GetLastProcessedEmailsResponseDto from '../../../../../core/dto/api/internal/GetLastProcessedEmailsResponseDto';
import MailDto                           from '../../../../../core/dto/modules/mailing/MailDto';

import CardWithTitleComponent              from '../../../../base-layout/components/cards/card-with-title';
import RowFontawesomeIconWithTextComponent from '../../../../other/row-fontawesome-icon-with-text';

export default {
  components: {
    'card-with-title'                : CardWithTitleComponent,
    'row-fontawesome-icon-with-text' : RowFontawesomeIconWithTextComponent,
  },
<...>

Child Component

<!-- Template -->
<template>
  <div class="col-12 col-lg-4 mb-4">
    <div class="card border-light shadow-sm">
      <div class="card-header border-bottom border-light">
        <h2 class="h5 mb-0">{{ cardTitle }}</h2>
      </div>
      <div class="card-body">
        <slot name="card-body"></slot>
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<!-- Script -->
<script>
export default {
  props: [
      "cardBody",
      "cardStyle",
      "cardTitle"
  ],
}
</script>

Despite consulting various resources such as documentation on named slots functionality, none of the sources offered a solution to my specific challenge.

Some of the references reviewed include:

Answer №1

I've come across a rather unsettling solution that Vue is overlooking empty arrays causing errors in the v-for loop.

Coming from other programming languages and frameworks, this issue shouldn't arise.

Here is the workaround:

<!-- Template -->
<template>

  <card-with-title card-title="Title">
    <template #card-body>
      <div v-if="[lastProcessedEmails.length]">

        <row-fontawesome-icon-with-text v-for="mailDto in lastProcessedEmails">
          <template #icon>
            <i class="font-weight-bold">
              <i v-if="mailDto.status === mailStatusSent"         :class="fontawesomeIconClassesSent"></i>
              <i v-else-if="mailDto.status === mailStatusPending" :class="fontawesomeIconClassesPending"></i>
              <i v-else                                             :class="fontawesomeIconClassesError"></i>
            </i>
          </template>

          <template #title>
            {{ mailDto.subject }}
          </template>

          <template #title-context>
            {{ mailDto.created }}
          </template>
        </row-fontawesome-icon-with-text>

      </div>
    </template>
  </card-with-title>

</template>

The root of the problem lies with:

  data(){
    return {
      lastProcessedEmails: [],
    }
  },

The array lastProcessedEmails gets updated through an Axios call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message from Object.create() indicates that the argument provided is not recognized as

Description Within my project, I am handling a JSON file, parsing it into an object, and attempting to transform it into an instance of the ProjectFile class using Object.create(). Code let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf- ...

Utilize a standard JavaScript function from a separate document within a function of a React component

I am facing an issue where I need to incorporate a standard JavaScript function within a React component function. The script tags are arranged in the footer in the following order: <script src="NORMAL JAVASCRIPT STUFF"></script> // function ...

What is the correct way to import the THREE.js library into your project?

I recently added the three library to my project via npm. Within the node_modules directory, there is a folder named three. However, when I tried to import it using: import * as THREE from 'three'; I encountered the following error: ReferenceEr ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...

Guide on Applying a Dynamic Color in VueJs 3 Composition API/Vuetify Using CSS

Currently, my project utilizes Vue 3 with the composition API and Vuetify for the UI. I am looking to utilize a color that is already defined in a Vuetify theme variable within my CSS, similar to how I have done it previously in JavaScript. Although I at ...

Dynamically taking input in Vue JS while using v-for loop

Hey there! I'm trying to get input in this specific manner: itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}] Whenever the user clicks on the add button, new input fields should be added ...

Ways to initiate SVG animations using Angular Component functions?

I am currently working on a project where I want to incorporate an animation that reflects the sorting process of an array of numbers. However, despite successfully sorting the numbers in the array, I am facing challenges with triggering the animations. I ...

Strategies for accessing the initial portion of an AJAX response

When using ajax to call an URL with dataType HTML, the response includes two parts such as accesstoken=1&expires=452. In this scenario, only the access token is needed. Using alert(response) displays both parts. How can the access token be extracted? ...

Tips for creating a stylish scrollbar in a React Material-Table interface

Currently, I am utilizing the react material-table and looking to implement a more visually appealing scroll-bar instead of the default Pagination option. Although I have experimented with the react-custom-scroll package, it has not produced the desired ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

Use JavaScript to dynamically generate a drop-down select menu

Is there a way to automatically expand a select menu dropdown using JavaScript or jQuery when a button is clicked? I am facing this challenge because I have a text field that allows users to input custom fields dynamically into a select input. My goal is ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

The Helper Text fails to display the error, and the error message does not appear when the login data is incorrect

Currently, I am facing an issue with displaying error messages within my helper text component while using Material UI. Despite successfully testing my backend code using Postman to identify errors, I am unable to see the error message under the button whe ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

Update Button Visibility Based on State Change in ReactJS

Currently, I'm utilizing a Material UI button within my React application. Despite changing the state, the button remains visible on the screen. Here's the relevant code snippet: function MainPage() { const state = useSelector(state => sta ...

Internet Explorer 11 Ajax problem

Once again, Internet Explorer is causing some issues. I have a file called validation.php where the values from a text box are sent for validation. The text box value is read and then a result indicates whether it is valid or not. This functionality work ...

`Animate your divs with slide in and slide out effects using

Currently, I am in the process of replicating a website and facing some challenges. This site is my inspiration for the project. I have managed to create a sliding effect using CSS, making the div slide in and out from the same direction. However, I want ...

Trouble with executing two asynchronous AJAX calls simultaneously in ASP.NET using jQuery

When developing a web application in asp.net, I encountered an issue with using jQuery Ajax for some pages. The problem arose when making two asynchronous Ajax calls - instead of receiving the results one by one, they both appeared simultaneously after the ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...