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

Using jQuery, prevent the user from entering text into an input box when a checkbox

In my project, there is a checkbox that determines whether an input box is disabled. The issue arises when I try to disable the input based on the database value. For example, when the value is 0, it should display as disabled false; however, the input rem ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

Changing the color of a marker on hover in Mapbox using leaflet.js

I have encountered an issue where setting the geojson triggers the mouseover event, causing an infinite loop and breaking functionality. I managed to fix it by changing it to click, but now I need to figure out how to make it work with hover. My goal is t ...

Synchronous async routes in Node Express

My express server requires fetching data from multiple external sources for each request, with the logic separated into various routers (some of which are not under my control). These routers operate independently, eliminating the need for one to wait on ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

Experiencing an excessive number of requests while managing the display of a spinner through axios interceptors

I have a single page application built with Vue (Webpack) where I am trying to manage the visibility of a spinner based on whether the app is currently processing an HTTP request or response. After following some tutorials, I implemented the event bus pat ...

Issue with Full-Calendar Vue refetching events; no visible changes occur

Attempting to refresh the calendar, but no changes seem to take effect. updatePlan () { //let calendarApi = this.$refs.fullCalendar.getApi() this.$refs.fullCalendar.$emit('refetch-events');//no visible changes are occurring } ...

React Native: How come my text is breaking like this and failing to adhere to the container's margin settings?

I am facing a challenge in React Native where I need to display multiple elements next to each other, with a flex wrap when there are too many elements or if the text is too long. Each element consists of an icon and text, with the text breaking into the n ...

I'm having trouble locating the documents I recently saved in my mongoose model

Here is my current challenge: I am populating a collection called "fruits" with some values. Once the data has been inserted, I want to use map to console.log each fruit individually. However, during the first attempt, instead of displaying a single fruit ...

"Efficient Ways to Manage Various File Types in React: xlsx, pptx, doc, docx

I am encountering an issue with downloading files in my React application. The API is functioning properly as confirmed using Postman, where different file formats such as xlsx, pptx, doc, docx, ppt and xls can be downloaded and opened successfully. Howev ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

Learn how to integrate Bootstrap with Vue.js TreeView in this tutorial

If you're looking to create a treeview using Vue.js, the code structure would resemble something like this: HTML: <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div ...

Getting to a nested key in a JSON object with JavaScript: a step-by-step guide

Currently, I'm working with a JSON file and need to extract the fileName tag for use. { "dataset": { "private": false, "stdyDscr": { "citation": { "titlStmt": { "titl": "Smoke test", "IDNo": ...

Switching an element from li to div and vice versa using Jquery Drag and Drop

I am currently experimenting with the following: Stage 1: Making the element draggable from li to div upon dropping into #canvas Placing the draggable element inside #canvas Stage 2: Converting the draggable element from div back to li when dropped i ...

Modify the JS/JQuery variable by utilizing the data entered into an HTML input field

I have implemented a javascript/ajax request on my advanced search page. <script> // window.setInterval(function() // { $(function () { var SearchTerm = '<?php echo $_POST['Search']; ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value. My objective is to set the initial width value of each div to 0% and then dynamically adjust it t ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

What is the process of accessing JSON data transmitted from a Express server in JavaScript?

Working with a node server, I've set up a client-server model, meaning the client connects to "localhost" and express generates a response based on certain logic. While I'm able to send a JSON object through the response, I'm unsure of how t ...