How to properly pass data between parent and child components in VueJS without using provide/inject

I've been experimenting with using provide and inject to pass data from parent to child elements, but I'm running into an issue where the data isn't available in the child element. It's strange because when I add the same data directly within the component (commented out), it's visible, but the injected data isn't showing up.

Hello is being printed, but not the passed data

TheResource.vue ---- parent

<template>
    <div>
        <base-card>
            <base-button @click.native="setSelectedTab('stored-resources')">Stored Resources</base-button>
            <base-button @click.native="setSelectedTab('add-resource')">Add Resource</base-button>
        </base-card>
        <component :is="selectedTab"></component>       
    </div>

</template>
<script>
import StoredResources from './StoredResources';
import AddResource from './AddResource';
export default {
    components:{
        StoredResources,
        AddResource
    },
    data(){
        return{
            selectedTab:'stored-resources',
            storedResources: [
                { 
                    id: 'official-guide',
                    title: 'Official Guide', 
                    description: 'The official Vue.js documentation',
                    link: 'https://vuejs.org'
                },
                {
                    id: 'google',
                    title: 'Google',
                    description: 'Learn to google.....',
                    link: 'https://google.org'
                }
            ]
        };
    }, 
    provide:{
        resources: this.storedResources
    },
    methods: {
        setSelectedTab(tab){
            console.log('Clicked')
            this.selectedTab = tab;
        }
    }
}
</script>

StoredResource.vue --- child

<template>

    <ul>
        <learning-resources v-for="res in resources" 
            :key="res.id" 
            :title="res.title" 
            :description="res.description"
            :link="res.link"></learning-resources>
        <h1>Hello</h1>
  </ul>
  
</template>
<script>
import LearningResources from './LearningResources';

export default {
   
    inject: ['resources'],
    //   data(){
    //     return{
           
    //         resources: [
    //             { 
    //                 id: 'official-guide',
    //                 title: 'Official Guide', 
    //                 description: 'The official Vue.js documentation',
    //                 link: 'https://vuejs.org'
    //             },
    //             {
    //                 id: 'google',
    //                 title: 'Google',
    //                 description: 'Learn to google.....',
    //                 link: 'https://google.org'
    //             }
    //         ]
    //     };
    // },
    components:{
        LearningResources
    }
}
</script>
<style scoped>
    ul{
        list-style: none;
        margin: 0;
        padding: 0;
        margin: auto;
        max-width: 40rem;
    }
</style>

Answer №1

According to the information provided in the Vue 3 documentation:

In order to access properties of a component instance, it is necessary to convert the provide method into a function that returns an object

provide() {
  return {
    resources: this.storedResources
  }
}

Without making provide a function, access to this is not possible

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

Confirming an authorization?

I have been working on this code and it is almost perfect, but I am struggling to understand why it needs to validate the 0 or 10 in order to work correctly. The issue I am facing is with a validation where the button should be deactivated when the counte ...

What is the best way to generate a static header in nextJS?

I am looking to create a static navbar without needing client-side fetching. Currently, I am using Apollo GraphQL and my _app.js file is set up like this: import React from 'react'; import Head from 'next/head'; import { ApolloProvider ...

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...

JavaScript - Automatic memory management following the execution of functions

After doing some research on garbage collection in JavaScript, I came across information stating that local variables of functions are collected once the function has returned (except for cyclical references which require breaking circles for the GC to fun ...

Building and deploying Nuxt 3 applications in different environments

Currently, I am in the process of configuring development and production environments within Nuxt 3 for testing purposes. Specifically, I want to utilize a test endpoint if the app URL begins with develop-, staging-, or test-. For instance, when accessing ...

Running a Redux Thunk action from within a TypeScript environment, beyond the confines of a React component

Currently, I am in the process of converting a React Native app into TypeScript. Unfortunately, I have encountered an issue with dispatching thunk actions outside of the store. Below is how my store is configured: store/index.ts import { createStore, app ...

Exploring the concepts of arc functions in discord/js programming

Example: Having trouble understanding how to create an arc in JavaScript based on a percentage input? Here's a simple explanation: feed it a percentage and it will create an arc that represents that percentage of a circle. I've managed to get t ...

Encountering issues while trying to establish a connection to MongoDB through JavaScript

I have developed a code for seamlessly integrating various social networking logins with nodejs. Below is my server.js file: // include the necessary tools var express = require('express'); var app = express(); var port = process.env ...

Difficulty establishing audio calls with Internet Explorer using PeerJS

I successfully implemented a user-to-user audio call system by following the steps outlined in this guide: The system is up and running flawlessly on my website while using Google Chrome. However, I encountered an issue when trying to connect to a user o ...

Encountering a dilemma during the docker build process with npm install is frustrating, especially when faced with an error message like: "Invalid response body when attempting

Encountering a docker build issue with npm install that seems to only occur inside the docker environment. The process works perfectly on my operating system Error Step 6/8 : RUN npm cache clear --force && npm install --legacy-peer-deps ---> ...

After ajax, trigger change event

Can anyone assist me in combining multiple functions within the same form using AJAX? The purpose of the form is to prenote a new "meeting" and it consists of an input for the date and a select dropdown for choosing the operator. FORM CODE: <div id=&qu ...

Securing pathways and pages using NextJs

I recently completed a project where I implemented route protection for a website using the if and else statements, assigning each page a function withAuth(). However, I have concerns about whether this is the most effective method for securing routes in n ...

Tips for retrieving data from a database with just one key press

There is a text field that triggers a JavaScript function when a key is pressed. <input type="text" class="text" id="txt_sh_vid" onKeyPress="vhc_record()" maxlength="4"> The function takes the input from the text field and searches for a result in t ...

Retrieve data from dropdown menu to showcase table using Node.js

I'm currently diving into learning nodejs and mongodb. My backend setup includes expressjs and mongojs, while ejs is handling the frontend of my application. The main goal is to allow users to select a class from a dropdown menu and view a correspondi ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

Leveraging the power of ES6, achieve recursion with requestAnimationFrame in

Lately, I've been working on creating a versatile SceneManager class that not only manages scenes but also handles rendering. class SceneManager { constructor() { this.scene = new THREE.Scene(); this.camera = new THREE.Perspectiv ...

The Vue error message indicates that the specified module, "../services/Repository", could not be located within the project

[SOLVED] After moving the services/ folder into the src/ directory, following the Vue.js Style guide, the error was resolved. Thank you for the help. Upon running npm run serve, an error occurred. Despite researching similar issues on Stack Overflow and a ...

Please ensure the previous v-dialog is closed before opening the next v-dialog

, I've been experimenting with a new vuetify project and have successfully added sign in and signup functionality using v-dialog. The issue I'm facing is that when I call these v-dialogs from multiple components, the previous dialog does not auto ...

Observing the Transformation When Employing *ngIf or *ngSwitchCase in Angular 2

Can someone lend a hand? I've run into an issue where my custom JavaScript function is not working after using *ngIf or *ngSwitchCase to change the view. Any suggestions on how to resolve this would be greatly appreciated. ...

Preview not showing CSS changes properly

1) I am encountering an issue with displaying CSS in a form preview tab. Despite setting the CSS, it does not reflect on the fields after clicking the preview button. 2) Are there alternative methods to open the tab in a new window rather than opening it ...