Leverage slot-specific information within the component's script in Vue

In my Vue project, I faced an issue where Component A has a slot that passes an object as slot-scoped to Component B:

Template of Component A:

<template>
<div>
   <slot :myObject="myObject" />
</div>
</template>

Template of Component B:

<template>
<component-a>
  <template slot-scope="{myObject}">
    <!-- using myObject here -->
  </template>
</component-a>
</template>

<script>
  module.exports={
     data(){
       return {
          myObject: null // This value never gets updated
       }
     }
  }
 </script>

While everything functions correctly in the HTML template of Component B, I encountered a roadblock when trying to access myObject in the script of Component B. One workaround could be creating a child component (C) that accepts myObject as a prop and handles all necessary logic there, but I am looking for an alternative solution.

Answer №1

When utilizing slot-scope, you are essentially transferring data to the slot from the component that hosts it, rather than with the content of the slot itself. In your scenario, if you intend to utilize data slot-scope, you need to pass the data from component A. Therefore, the data-source myObject must be present in component A.

The appropriate method would resemble the following:

Component A

<template>
    <div>
        <slot :myObject="myObject" />
        <button @click="changeMyObject">Change MyObject</button>
    </div>
</template>
<script>
    export default {
        name: "slot-scope-component",
        data(){
            return {
                myObject: {
                    value: "ABC"
                }
            }
        },
        methods:{
            changeMyObject() {
                this.myObject = {
                    value: "XYZ"
                };
            }
        }
    }
</script>

Component B

<template>
    <ComponentA>
        <template slot-scope="props">
            {{props.myObject}}
        </template>
    </ComponentA>
</template>

<script>
    import ComponentA from '@/components/ComponentA';

    export default {
        components: {
            ComponentA
        },
    }
</script>

A minor spelling error was also noted: You had written slot-scoped instead of slot-scope

You can enhance the code further by employing destructuring:

slot-scope="{myObject}"

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 to toggle the selection of multiple checkboxes

Let's start fresh, no need to worry! This is simply a jQuery question ;) I am currently working on a PHP code where the user sends a query to our database. The form then displays sets of results grouped in tables, each with checkboxes to select the d ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...

What distinguishes node from node js?

Following the instructions on https://nodejs.org/en/download/package-manager/, I installed Node.js. Upon checking the current version using: :~/Downloads$ nodejs -v I discovered that I was running v4.2.6, which is an older version. Deciding to update, I ...

When loading a page with Puppeteer using the setContent method, images may not be loaded

Currently, I am experiencing an issue with Puppeteer where it does not load resources that are specified with relative paths (such as background.png in the image src or in CSS url()). When I try to load the content of a local file using setContent(), the o ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

What is the process for locating the src value of an image that has been uploaded utilizing fileReader?

I am currently working on a program that empowers the user to select an image for uploading. Once the user chooses an image, it activates the previewFile() function, which makes use of FileReader to display the selected image. Now, I'm in the process ...

Issues related to the performance of React, Redux, and three.js

UPDATE: After identifying the issue, I have narrowed it down to this small gist and this jsfiddle. In my real-time 3D game based on three.js, I intended to utilize Redux for state management. Despite creating a simple prototype for testing purposes, even ...

Guide to displaying JSON.stringify data in PHP

I am attempting to retrieve my Google contact list using the Contact API. I have successfully retrieved the result and it is displaying in the console of both Chrome and Firefox browsers. However, I want to print this data using PHP on the same page. < ...

After an error occurs, the Node.js Restify code will be executed

Within a Restify route, I have set up a router handler that calls a custom module for error checking. If the code encounters an error condition, it returns next(err) and displays the error message in the browser. However, the code does not stop executing a ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

Display a hyperlink in an iframe on the main page from a different domain using JavaScript

I'm currently using Angular with Wirecard as my payment provider. When I need to add a payment, I open an iframe that directs the user to the Wirecard site to accept the payment. Once the user clicks accept, I provide a link back to my site from Wirec ...

What is the best way to verify a password's strength with Joi so that it includes 2 numbers, 2 special characters, 2 uppercase letters, and 2 lowercase letters?

Is there a way to achieve this using Joi? For instance: Joi.string() .required() .min(8) .max(16) .pattern(/(?=(?:.*[a-z]){2,16}).+/) .pattern(/(?=(?:.*[A-Z]){2,16}).+/) .pattern(/(?=(?:.*[0-9]){2,16}).+/) .pa ...

What is the process for exporting Three.js files to .stl format for use in 3D printing?

I stumbled upon a page with this link: Is it possible to convert Three.js to .stl for 3D printing? var exporter = new THREE.STLExporter(); var str = exporter.parse(scene); console.log(str); However, despite using the code provided, I am unable to export ...

Instructions for bringing the v-overlay element into view as soon as the page loads

Currently, I am in the process of developing an application using Nuxt v3.9.3 and Vuetify 3.5.1. I have incorporated the "absolute" link below into my implementation, which displays an overlay when a button is clicked. <template> ... <div id=&qu ...

Bringing in an external .js file into nuxt.config.js

Having trouble importing config.js with the project's API keys and getting undefined as a return value. //config.js var config = { fbAPI: "key" } - //nuxt.config.js const cfg = require('./config') env: { fbAPI: cfg.apiKey } Wonder ...

Executing two Ajax calls in ReactJS with different parameters can improve the efficiency of your

Why does the second Ajax call overwrite the first one, causing the results to be different each time I refresh it? In the first Ajax call, I have set tests: [], testsHistories: [] in the setState function. However, the second Ajax call only sets the stat ...

Make sure to prevent losing the global status in Vuex and VueRouter when the page is refreshed

As I develop a Single Page Application (SPA), I am utilizing Vuex to manage session states on the client side. However, I have noticed that the state resets whenever the browser is manually refreshed. Is there a way to prevent this behavior without relying ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Sorry, the server cannot be reached at the moment. Please try again later

Recently delving into Node.js and just getting started on using MongoDB. Currently establishing a connection with my MongoDB Cluster that I have set up. const dbURI = 'mongodb+srv://testuser:<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

What is the method to render certain text as bold using a json string?

I need assistance with concatenating two strings in react while ensuring that the first string is displayed in bold, while the second one remains unchanged. The first string I want to emphasize is stored in a JSON file, and the second string comes from an ...