The functionality of Vue slot-scope seems to be restricted when used within nested child components

Here is the component configuration being discussed:

Vue.component('myComponent', {
    data () {
        return {
          msg: 'Hello',
        }
      },
    template: `
      <div class="my-component">
          <slot :msg="msg"></slot>
      </div>
    `,
})

The issue arises when trying to bind the msg value inside the grand-child element by calling out the component from a template like this:

<my-component>
    <div class="parent">
        <div class="child">
            <div class="grand-child" slot-scope="{ msg }">
               {{ msg }}
            </div>
        </div>
    </div>
</my-component>

This raises the question of whether slot-scope is restricted to the direct child element, and if so, why?

Answer №1

Does slot-scope work only on the direct child element, and if so, why?

Indeed, slot-scope is limited to the direct child element within a component. This limitation exists because the <slot> element in the component gets replaced by the provided content. When Vue encounters the slot-scope attribute specifically placed on the component's content element (e.g., your <div class="parent">), it associates all v-bind attributes found within the <slot> with that specific namespace.

Here's an illustrative example:

Vue.component('myComponent', {
    data () {
        return {
          msg: 'Hello',
        }
      },
    template: `
      <div class="my-component">
          <slot :msg="msg"></slot>
      </div>
    `,
})
new Vue({el: '#app'})
.parent, .child, .grand-child {
  border: 1px solid;
  padding: 2px;
}
.parent:before, .child:before, .grand-child:before {
  content: attr(class);
  display: block;
  color: #999;
  font-size: 0.8em;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9a9989acbecadacecfcacd">[email protected]</a>/dist/vue.min.js"></script>
<div id="app">
<my-component>
    <div class="parent" slot-scope="{ msg }">
        <div class="child">
            <div class="grand-child">
               {{ msg }}
            </div>
        </div>
    </div>
</my-component>
</div>

To delve deeper into this concept, consider that Vue treats all HTML elements as render functions. Consequently, when replacing the <slot> with its content, Vue primarily focuses on the root element for evaluating attributes and data bindings, disregarding any nested hierarchy beneath that root element.

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

Steps to update the first set of x documents in MongoDB using Mongoose

Is there an efficient way to update the first five documents in mongoose? While I am familiar with updating multiple documents based on a condition, I specifically want to target the first five documents for updating in mongoose. I understand that I can a ...

JavaScript change the object into a string

I've been working on code to convert strings into dictionaries and arrays, and vice versa. While string to array and string to object conversions are successful, the reverse process is giving me trouble. I'm currently stuck and unsure of how to r ...

Having trouble with Vue @click.native not responding?

My navigation component looks like this: <template> <nav class="navbar navbar-default navbar-fixed-top"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar ...

Unending React cycles - invoking setState() within a render onClick

Recently delving into React and facing an issue with rendering a button component. My goal is to create a button that, upon being clicked, fetches data and displays it as a list below the button. To achieve this, I am attempting conditional rendering. I ut ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...

Unable to retrieve the contents of a previous shopping cart

I need to update my shopping cart. I am trying to retrieve the information from my old cart, but for some reason, it's not working properly and I keep getting a quantity of 1. Below is the code for the app.post request: app.post("/add-to-cart/:i ...

I'm a beginner with Angularjs and I attempted to populate multiple JSON values, but unfortunately, it didn't work as expected

<div ng-controller="studentController" ng-repeat = "student in students | unique = 'RollNo' " > <table class="profile-info"> <tr> <th>Enrollment Number</th> <td> ...

I am interested in displaying the PDF ajax response within a unique modal window

With the use of ajax, I am able to retrieve PDF base64 data as a response. In this particular scenario, instead of displaying the PDF in a new window, is it possible to display it within a modal popup? Any suggestions on how this can be achieved? $.ajax ...

Update the axios authorization header based on updates to the store

As someone who is more familiar with React, I am new to Vue and encountering a specific issue. axios.js import store from '../../store/index'; import axios from 'axios' const API_URL = process.env.API_URL; const token = store.getters ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

Unlocking the full potential of parsing messages using google protobuf-js

Currently, I am developing a front-end application using Angular5+ that utilizes google-protobuf JS and WebSocket for backend communication. Within my .proto files, I have defined 2 objects: a Request object. a Notification object. I have created a han ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Unable to utilize jQuery library in AngularJS partial HTML files, despite being loaded in the index.html file

I have been working with a web template that utilizes jQuery image gallery and other elements. Now, I am looking to convert this template into an AngularJS structure. To do so, I have created partial HTML pages like slider.html or contact.html along with t ...

Utilizing visual elements to change the options of a dropdown menu

I am currently working on creating a form for a client who has requested a map of the city to allow visitors to visually select their location. They want this feature to link to the City Dropdown/Select area of the form. Here is a link to the client' ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

Choose an option using jQuery with the ability to navigate to the previous or next

I encountered a bug when I tried to click the next or previous button. Below is the HTML code snippet: $("#nextPage").click(function() { $('#pagination option:selected').next().attr('selected', 'selected'); console.log( ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

Issue with Webpack failing to bundle a custom JavaScript file

Here is the structure of my directory: Root -dist -node_modules -src --assets --css --js --scss --index.js --template.html --vendor.js package-lock.json package.json postcss.config.js tailwind.config.js common.config.js development.config.js production.co ...