Leveraging Vue slots to display a component inside another component

I am currently working on creating a base modal component that can be re-used, utilizing slots to insert the modal content. The issue I am facing is that when the modal is triggered by clicking a button, it displays without any content present. How can I ensure that my content appears within the designated slot? Am I misunderstanding how slots work?

To better illustrate my problem, here is a fiddle link: https://jsfiddle.net/70yyx8z2/19/

// registering the base modal component
Vue.component('modal', {
  template: '#modal-template'
})

// registering the content component for the modal
Vue.component('modal-content', {
  template: '#modal-content'
})

// initializing the Vue app
new Vue({
  el: '#app',
  data: {
    showModal: false
  }
})


<modal v-if="showModal" @close="showModal = false">
  <h3 slot="header">Header goes here</h3>
  <!--
    How can I correctly utilize the slot to render the modal content component?
  -->
  <modal-content></modal-content>
</modal>

Answer №1

Check out this JsFiddle

Including a slot name within the component is not effective because it will not be mounted before the slot replacement happens. Instead, you should assign the component to the slot.

<!-- code for modal content component -->
<script type="text/x-template" id="modal-content">
  <form>
    <h2>This content should display...</h2>
    <input type="text" placeholder="user name" />
  </form>
</script>

<!-- app section -->
<div id="app">
  <button id="show-modal" @click="showModal = true">Show Modal</button>
  <!-- utilizing the modal component and passing in a prop -->
  <modal v-if="showModal" @close="showModal = false">
    <h3 slot="header">Header content here</h3>
    <!--
      How can slots be utilized to render the modal content component?
    -->
    <modal-content slot="body"></modal-content>
  </modal>
</div>

UPDATE: Made a correction in terminology based on feedback from @thanksd

Answer №2

Essentially, all you have to do is follow these steps.

<content-container slot="main"></content-container>

It may be advisable to eliminate the container-element from the content-container component.

Check out your updated fiddle here.

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

Ways to move the cursor to the search field after the placeholder text

I'm working on a Vue project with a small app featuring an input type search. The issue I'm facing is that the cursor appears at the beginning of the input, whereas I want it to appear after the placeholder text. How can I make this adjustment? ...

In iOS devices, the Ionic framework restricts the ability to open links in a new tab using the ng-href attribute

In my quest for mobile functionality, I'm aiming to implement a feature on devices where tapping will open 'codepen.io' (triggered by ng-click), and tap and hold will display a context menu with the option to 'Open In New Tab', red ...

Guide on inserting a new column into an array of objects in Vue

Below is the fetch method I have defined to retrieve recordings from the database. However, I need assistance in adding a new column to each record specifically for frontend purposes. Can someone help me with this problem? <script> export default { ...

How can I prevent getting stuck in a never-ending React re-render cycle?

I always believed that placing any form of setState within a useEffect call would lead to an endless re-render loop since the useEffect gets triggered on every render. Surprisingly, in my Next.js application, everything seems to be functioning well without ...

"Learn how to capture the complete URL and seamlessly transfer it to another JavaScript page using Node.js and Express.js

Is there a way to access the token variable in another page (api.js)? I need to use it in my index.js. var express = require('express'); var router = express.Router(); router.get('/', function(req, res ...

The <b-list-group-item> component in a Vue.js CLI application using bootstrap-vue is failing to render

My Vue-CLI app uses Bootstrap-vue and axios to fetch JSON data. The HTML code in my App.vue displays the data using UL and LI tags: <p v-if="loading">Loading...</p> <ul v-else> <li v-for="(value, key) in post" :key="key"> ...

What is the reason behind using V-for to show identical code instead of the actual values stored in the object?

I am currently learning Vue.js and practicing using the loop feature in it. However, I am facing an issue where when I try to retrieve data from my app.js file into my welcome blade file, it only displays the variable I wrote in the code rather than showin ...

Using React Hooks to render radio buttons within a map iteration

My code contains a nested map function where I try to retrieve values from radio buttons. However, the issue is that it selects all radio buttons in a row instead of just one. Below is the snippet of my code: <TableHead> <TableRow> ...

Vue 3 - Dealing with "Module Not Found" Error for PNG Files containing spaces in the file name

Issue Recap Recently, I added an image called foo - compressed.png to the assets folder and updated a component to include it like this: ... <img src="../../assets/bar-compressed.png" /> <img src="../../assets/foo - compressed.png& ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Step-by-step guide: Uploading files with Ajax in Codeigniter

I am facing an issue with updating data and uploading an image when editing a row in my grid. Although the data is successfully updated, I am encountering difficulties in saving the image file to a folder. Here is what I have tried: While using AJAX, I ...

Establishing the Default Volume within a script

I'm looking to adjust the default volume of music on my website. Currently, it plays too loudly on load, but I have a slider bar that allows users to change the volume. How can I set the default volume to be 25% of the slider? CHECK OUT MY WEBSITE! ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

Updating props in real-time

In the scenario described below, my application features a template containing a custom component. The data is transmitted from Template A to the custom component as props (":list") Template A: <template> ... <custom-component v-for="li ...

discord.js fails to provide a response

const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Clien ...

Unusual patterns observed when employing the splice method in AngularJS for ordering

Take a look at this Plunker demo link I have encountered an issue after implementing the orderby feature (line 24) in my application. When I try to add an item without priority and then add another one with priority, followed by deleting the first item, t ...