Passing slots to child components within a VueJS application - A helpful guide

Within my application, I frequently utilize a list and list_item component. To provide a general idea:

contact_list.vue

<template lang="pug">
    .table  
      .table-header.table-row
        .table-col Contact
        .table-col Info

      .table-body
          contact-list-item(v-for='contact in contacts',
                            :contact='contact',
                            @click='doSomething()')

</template>

contact_list_item.vue

<template lang="pug">
.table-row(@click='emitClickEvent')
  .table-col {{ contact.name }}
  .table-col {{ contact.info }}
</template>

For instances where I use the contact_list within a specific component, I aim to include a slot that adds additional columns to the contact_list_item component. This slot will utilize data from the particular contact being displayed in the contact_list_item component to create these extra columns.

What would be the best approach to achieve this? Would using slots be recommended?

Thank you in advance.

Answer №1

To implement slots effectively, you will need to utilize a scoped slot for the contact-list-item component. If you are unfamiliar with Pug, you can use HTML as shown in the example below.

Within the contact-list component, make sure to include a slot. This allows us to pass the contact as a property and leverage scoped slots.

<div class="table">
  <div class="table-header table-row">  
    <div class="table-col">Contact</div>
    <div class="table-col">Info</div>
  </div>
  <div class="table-body">
    <contact-list-item v-for='contact in contacts'
                       :contact="contact"
                       @click="doSomething"
                       :key="contact.id">
      <slot :contact="contact"></slot>
    </contact-list-item>
  </div>
</div>

Include a slot in the contact-list-item as well.

<div class="table-row" @click="emitClickEvent">
  <div class="table-col">{{contact.name}}</div>
  <div class="table-col">{{contact.info}}</div>
  <slot></slot>
</div>

Finally, in your Vue template, use the scoped template feature.

<div id="app">
  <contact-list :contacts="contacts">
    <template scope="{contact}">
      <div class="table-col">{{contact.id}}</div>
    </template>
  </contact-list>
</div>

For a working example of this implementation, check out this CodePen demo. Note how the id column is now displayed within the contact-list-item.

Answer №2

Utilize the template tag to register a slot within a child component.

Sometimes, there may be a need for multiple named slots.

child.vue

<template>
  <div>
    <h2>I have become a father now</h2>
    <grandchild :babies="babies">
      <template v-for="(baby, id) in babies" :slot="baby.name">
        <slot :name="baby.name"/>
      </template>
    </grandchild>
  </div>
</template>

grandchild.vue

<template>
  <div>
    <p v-for="(baby, id) in babies" :key="id">
      <span v-if="baby.isCry">Owe...owe...</span>
      <slot :name="baby.name">
    </p>
  </div>
</template>

parent.vue

<template>
  <div>
    <h2>Time to visit grandpa</h2>
    <child :babies="myGrandChilds">
      <button slot="myGrandChilds[2].name">baby cry</button>
    </child>
  </div>
</template>

Answer №3

Contribute to @DrSensor's response.

When working with Vue3, it is recommended to utilize dynamic slot names.

<template>
  <div>
    <h2>I've become a parent now</h2>
    <grandchild :babies="babies">
      <template v-for="(baby, id) in babies" #[baby.name]>
        <slot :name="baby.name"/>
      </template>
    </grandchild>
  </div>
</template>

Answer №4

If you're looking to easily move multiple slots down a level, check out the technique outlined in this reference. By making slight adjustments, you may even be able to transfer them further down.

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

Utilize Google Maps to receive directions to a specific destination and discover current traffic conditions along the route using their comprehensive API

I am currently working on implementing the Google Maps direction identifier functionality with traffic details. However, I am able to obtain directions but not specific traffic details for a selected path; it seems to apply overall traffic data instead. ...

Upgrading from synchronous $.ajax() to AngularJS $http or vanilla JavaScript (XHR) for asynchronous calls

Presented below is a function that I am currently working with: function getDataAvailablity() { var isDataAvailable; $.ajax({ url: 'http://someurl/data.json', async: false, dataType: json }).success(function() ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: https://i.sstatic.net/Y0Seo.png Is there a simple method to transform it into a semicircle like shown here? https://i.sstatic.net/D8bKu.png ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Guide to effectively utilizing Vue slot-scope feature within nested components

I am currently facing difficulties in understanding the proper usage of the slot-scope attribute and comprehending the documentation. Below is a simplified version of my requirement. You can view it in action here: https://jsfiddle.net/4j4zsy0g/ Main Cod ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

Tips for styling the json response received from a servlet with jquery ajax

I am attempting to display a list of users returned from a servlet using jQuery ajax. The first script block is functioning well, successfully presenting the list of users in a formatted manner but experiencing issues passing form parameters such as text a ...

The utilization of a combobox in VueJS 3 alongside the Mitt event bus

I've set up mitt as a global event bus in my main.js: import { createApp } from "vue"; import App from './App.vue' import mitt from "mitt"; const emitter = mitt(); const app = createApp(App); app.config.globalProperties.emitter = emitter; ap ...

The "useState" React Hook is restricted from being used in a class component. To utilize React Hooks, they can only be invoked within a React function component or a custom React Hook function

I am relatively new to React frontend development and I am currently working on adding a temporary drawer to my Material-UI NavBar. Here is the code snippet where I added the drawer: class Navbar extends Component { render() { const { authentic ...

The escape character appears to be misunderstood, causing an error due to an invalid escape sequence

When using the following syntax: executeJSCommand("location.href='StatusDetails.php?CHLD=1\&JNum=1024&JTitle=';"); An error occurs displaying: Invalid Escape Sequence ...

Is there a way to programmatically simulate clicking on the "Cancel search" button?

I have a text input field with type "search". In order to perform UI testing, I need to simulate clicking on the "cancel search" button: https://i.sstatic.net/ahcwQ.png The code for this specific input field is as follows: <input type="search" value= ...

jQuery effects failing to run properly in Internet Explorer

<script type="text/javascript" src="css/jquery-1.7.1.js"></script> <script type="text/javascript"> function slidedown(id){ $('#rerooftext').hide(0); $('#inspectiontext').hide(0); $('#remodelingtext').hid ...

"Discover the process of incorporating two HTML files into a single HTML document with the help of

I successfully created both a bar chart and a pie chart using d3.js individually. Now, I am trying to load these charts into another HTML file using jQuery. $(document).ready(function() { console.log("ready!"); $("#piediv").load("file:///usr/local ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

The module you are trying to access at './server/controller/controller.js' does not contain an export with the name 'default'

I'm fairly new to backend development and I've recently started using ES6 modules in my project. However, when I try to import the controller file into index.js and run the project, I encounter the following error: Syntax Error: The requested mo ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

Click event for jQuery horizontal accordion

I'm attempting to create a simple horizontal accordion-style element. My setup includes three 'banner' divs and three 'area' divs. Ideally, when I click on a banner, the corresponding area should animate - expanding in width to au ...