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

What could be causing the card hover to extend beyond the container limits?

Whenever I hover over the card, it seems to extend beyond the main container, making it difficult for me to click on the navigation bar. I attempted to place it inside both v-content and v-container, but unfortunately, it still doesn't seem to work a ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

What is the correct way to update the state of an object in ReactJS using Redux?

Hello, I am facing an issue with storing input field values in the state object named 'userInfo'. Here is what my code looks like: <TextField onChange={this.handleUserUsername.bind(this)} value={this.props.userInfo.username} /> ...

delay of Paypal API disbursement for transactions with a range of money values

After browsing through various resources such as this link, that link, and another one on the PayPal developer website, I attempted to implement a payment processing system that allows users to approve a preset amount of money. Similar to services like Ube ...

To ensure the smooth functioning of a React application running on a Docker container in Ubuntu 16.04, it is

I'm currently in the process of setting up a docker container for running a react app that sends a fetch request to another docker container containing a node server. The deployment is on Ubuntu 16.04, however, after building and deploying the contain ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...

How to retrieve the name of a node using partial text in JavaScript

I am looking for a way to separate values into key-value pairs before and after a specified delimiter (:) in JavaScript. For example: Product Name: Product 15 Product code: 1234 If I search for "product," I want to retrieve the product name and product c ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

JavaScript issue: "No relay configuration found" error specifically occurs in Internet Explorer versions 7 and 8

Encountering issues with loading JavaScript only on specific pages in Internet Explorer. Safari, Firefox, and Chrome render the page correctly. Debugging revealed the following errors: 1) No relay set (used as window.postMessage targetOrigin), cannot send ...

Handling Posts and Gets with Jquery/Javascript

Working on a web application that involves generating numerous post and get requests. I am able to monitor all the requests using Developer Tools in Mozilla/Chrome, as well as with Charles (an app). Is it feasible to develop a jQuery or JavaScript functi ...

Utilize Electron's fs to stream a file directly to an HTML video player while it is being downloaded

I am currently exploring the possibility of using the HTML video player to stream a file from the file system within Electron. My goal is to initiate streaming while the file is still being downloaded. I am uncertain whether my current approach will be ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

Retrieving the current date in React from a distinct date format

Does anyone know how to retrieve today's date in the following format using React? "2019020420" I have a function that currently retrieves the current date. How can I modify it to output the desired date format shown above? getCurrentDate( ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

The process of ensuring a component updates upon clicking on it

In the process of creating a to-do app, I am working on implementing an edit mode for tasks. My goal is to have a task title that expands into task details when clicked (using Collapse from MUI). Additionally, I aim to enter into an edit mode by clicking o ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

Storing the selected radio button value in AsyncStorage using React Native: A step-by-step guide

Can anyone help me with storing the users selected radio button value in AsyncStorage? I have radio button values being retrieved from another file and assigned to labels. Here is an example of how my radio buttons are structured: import RadioButtonRN fr ...

Is there a way to achieve element scrolling similar to scrollLeft within a scrollable container without using JavaScript

Looking for a CSS Solution: Is there a way to achieve element.scrollLeft functionality in CSS without using javascript? I want to pre-scroll a scrollable container. Situation Overview: I have a scrollable container that houses various items. Some instanc ...

When using the `Node fs.readstream()` function, the output includes `<Buffer 3c 3f 78 6d 6c ...>`, which is not in a readable

Handling a large XML file (~1.5gb) in Node Js by streaming it to process data in chunks has proven challenging due to the complexity of the documentation. A simple code snippet I am currently using is: var fs = require('fs'); var stream = fs.c ...

Styling delays on initial Nuxt / Vue.js render or page refresh

While delving into the world of Nuxt/Vue, I've come across a rather odd issue that has me scratching my head. All components' styles seem to be loading at a snail's pace during rendering, even in a "dev" environment. I'm eager to uncov ...