Leveraging data stored in a parent component within a child component in Vue.js

Working with Laravel Spark, I have implemented a component within another component.

<parent-component :user="user">

   <child-component :user="user" :questions="questions"></child-component>

<parent-component>

Inside the parent component, I have a data method containing questions data:

props: ['user'],
data(){
    return {
        questions: {
            // these values are set in another method within this file
        },
    }
},

As shown, I have passed :questions to the child component in order to utilize the questions within that component for looping purposes.

Within the JavaScript file for the child component, I have:

props: ['user', 'questions'],

However, when attempting to access the questions, I am only receiving a default object unlike the user data which contains all the relevant information.

Could you please provide guidance on the correct approach to resolving this issue, as I am currently only guessing...

Below is the JavaScript file for the child component:

Vue.component('control-question-navigation', {
    props: ['user', 'questions'],
    data() {
        return {
        //
        }
    },
    methods: {
    },
    mounted() {
        var $this = this;
        console.log($this.questions); // returns standard object
        console.log($this.user); // correctly returns user data
    }
});

Answer №1

It appears that there may be an issue regarding the compilation scope in your template setup.

It seems like you are utilizing a concept known as Content Distribution with Slots, but with incorrect scoping for template variables.

For more information, you can refer to this link: https://v2.vuejs.org/v2/guide/components.html#Compilation-Scope

According to the documentation:

One simple rule to follow for component scope is that everything in the parent template is compiled within the parent scope, while everything in the child template is compiled within the child scope.

Based on what you've shared, it seems like the following template lines belong to your main component:

<div id="app">
    <parent-component :user="user">
       <child-component :user="user" :questions="questions"></child-component>
    <parent-component>
</div>

In this scenario, the `user` is already within the root component, making it accessible to both `parent-component` and `child-component`. However, the `questions` variable is defined within `parent-component`, not at the root level.

As per the compilation scope guidelines provided in the link above, you should also have `questions` defined at the root level alongside `user`. Alternatively, you could move the template of the parent component into its own Vue file or within the template string of the `parent-component` definition.

UPDATE: Potential solutions for better clarity

Option 1: Define your root component and include `questions` within it along with `user`:

new Vue({
    el: '#app',
    data: {
        user: "test user",
        questions: ["one", "two", "three"]
    }
});

With this setup, both `user` and `questions` will be accessible to both `parent-component` and `child-component`.

Option 2: Instead of using Content Distribution with Slots, you can utilize a template string:

Vue.component("parent-component", {
    template: `
        <child-component :user="user" :questions="questions"></child-component>
    `,
    props: ["user"],
    data: function() {
        return {
            questions: {} // You can initialize this within a local method here
        }
    }
    // ...
})

By doing this, your `child-component` will be able to access `this.questions` from your `parent-component`.

Answer №2

   data: {
        // these values will be initialized elsewhere
    }

To achieve the desired outcome, you should consider using a computed property.

computed: {
  questions(){ return this.initializeQuestions() }
},
methods: {
  initializeQuestions(){ return /* list of questions */ }
}

Make sure to update the method to return the list of questions instead of modifying component data directly. The template structure is correct; it's just a matter of placing the logic in the appropriate location.

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

Expansive image coverage

My footer design includes a rounded left image, a repeating middle section, and a rounded right image. How can I ensure that it scales perfectly responsively without overlapping? Ideally, the solution would involve adjusting the width of the middle section ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...

Combining two arrays containing objects in JavaScript

Imagine having 2 arrays of objects that you want to merge in a parallel manner. For instance var array = [{foo: 2} , {boo: 3}] var array2 = [{foo2: 2}, {boo2: 4}] The outcome would be var array3 = [{foo:2,foo2:2},{boo:3,boo2:4}] In what way can this be ...

A dynamically-generated dropdown element in the DOM is being duplicated due to JavaScript manipulation

Currently, I am dynamically adding a dropdown element to the page using javascript. The goal is for this dropdown to modify the properties displayed on a map. However, when attempting to add the element after the map loads, I encounter an issue where the d ...

Build.js.erb requesting a partial script task

Struggling to make my create action function accurately in my rails app. The following two lines work as intended: $('#pit_form').remove(); //remove form $('#new_link').show(); //show new link again They successfully remove the form ...

Is there a way to ensure a function is only executed once whenever the page is refreshed?

I have the following code snippet: function myfunc () { alert('executed'); } $('.classname').on('click' function () { myfunc(); }); I am trying to ensure that myfunc is only executed once. I don't want it to ru ...

Navigating directories and file locations in a Node/Express application

An example of my Node/Express app's file structure is shown below: /lib coolStuff.js /routes funRoute.js /views sickView.hbs app.js In the past, I have been using relative paths like var coolStuff = require('../lib/coolStuff'); to re ...

What is the method to ensure that the Node REPL solely displays the result?

Is there a way to execute a script in Electron that only logs the output value without displaying all the code? I am utilizing xterm.js and node-pty for this project. For instance, consider the following sample code: // Add your code here function multi ...

The ajax form submit function does not have the capability to automatically post content

On this particular webpage, there is a visible form labeled form A which contains a submit button with a post action. <form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> I am looking to cre ...

MERN stack does not have a defined onClick function

I am developing a website for college registration, and I encountered an issue while trying to create a feature that allows students to select a major and view all the associated courses. I made a list of majors with buttons next to them, but whenever I at ...

Is it common for browsers to continuously store compiled versions of script elements in their cache?

When using a web application that allows users to interact with javascript, they are required to include a function main() in their "program". The interface includes a "run" button and an "edit" button. Clicking the "run" button executes text from a <te ...

Achieve self within a dynamically loaded module

I recently followed a tutorial on creating a dynamic sidebar toggle using Vue and Vuex, which you can access here. However, I encountered an issue with implementing a "close" button within the sidebar component. It seems that I cannot access 'this.co ...

Setting up a Vue.js application within a nested subdirectory

I just completed creating a vue.js app with vue-cli 3.0 and it's working perfectly. Now, my goal is to deploy it in production, but I need to deploy it under a subfolder instead of the root directory, like this: https://example.com/myvueapp/* I hav ...

Clicking on Only One Card in Material UI React

I've encountered an issue with my code: const useStyles = makeStyles({ card: { maxWidth: 345, }, media: { height: 140, }, }); export default function AlbumCard(props) { const classes = useStyles(); let ...

Prevent sticky div from overlapping with footer

I currently have a social link menu that is fixed to the left side of my page, structured like this: <footer id="colophon"></footer> <div> <nav> <ul id="social"> <li>Link1</li> ...

Issue with casl: can() method returns null upon page refresh using F5 command

I've been working on implementing the CASL permissions system into my VueJS 2 project. Everything seems to be working fine, but I have encountered an issue when intentionally refreshing the page (like pressing F5). After the refresh, all can() functio ...

Encountering the error message "Error: Unable to process rejection (TypeError): that.setState function is not defined" while using ReactJS

I've been working on a dynamic chart that changes based on the Slider value. I did some research and everyone suggests that I need to bind it to resolve this error. However, no matter how many times I try to bind the function in different ways, I keep ...

What is the best way to utilize a single AngularJS 1.5 component multiple times within a single view?

While working on a project using AngularJS 1.5's new components, I encountered an issue with widget isolation. It seems that when I use the same widget multiple times, they end up sharing their controller or scope. I was under the impression that comp ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

Mastering the management of types for injected properties within the Vue Composition API when using Typescript

import firebase from 'firebase' import Vue from 'vue' /* The following file imports necessary types from firebase and extends the Vue instance */ declare module 'vue/types/vue' { interface Vue { $fireStore: firebase.fir ...