Child components are not able to access properties from the root component in VUE3

Hi there! I'm currently learning VUE3 and had a question about defining global properties in the Root Component. I did some research on Google before posting this question, but couldn't find any relevant results.

I would like to set a global property in the Root Component that can be accessed by all child components. This property could be something like a BASE_URL link or a TITLE.

Below is my Root Component:

<script>
    import HeaderTop from './pages/partials/header_top.vue'
    import HeaderMiddle from './pages/partials/header_middle.vue'
    import MainNavbar from './pages/partials/main_navbar.vue'
    import MainFooter from './pages/partials/footer.vue'

    export default {
        data() {
            return {
                show: true,
                baseURL: 'www.example.com' 
            }
        },

        mounted() {
            this.show = true;
        },

        components: {
            HeaderTop,
            HeaderMiddle,
            MainNavbar,
            MainFooter
        }
    }
</script>
<template>...</template>

HeaderMiddle.vue component:

Here, I want to access the property defined in the Root Component.

<script>
    import app from '../../RootComponent.vue';

    export default {
       
       // I have tried this approach as well but it didn't work
       data() {
        return {
            baseURL: app.baseURL
        }
       }
    }
</script>
<template> 
<div class="container-fluid">
    <div class="row text-center align-items-center height-150">
        <div class="col-xs-12 col-sm-12 col-lg-2">
            <div class="logo">
            <a href="/" title="">

                <h1>{{baseURL}}</h1>  <!-- This doesn't work -->
                <h1>{{app.baseURL}}</h1> <!-- This doesn't work -->
                <h1>{{app.baseURL}}</h1> <!-- This doesn't work -->

            </a>
            </div>
        </div>
     
    </div>
</div>
</template>

App.js:

require('./bootstrap');

import { createApp } from 'vue';
import router from './router'
import RootComponent from './RootComponent.vue'
 
const app = createApp(RootComponent);
 
app.use(router).mount("#app");

Answer №1

One suggestion is to define the baseUrl as a global property in your Vue application:

require('./bootstrap');

import { createApp } from 'vue';
import router from './router'
import RootComponent from './RootComponent.vue'
 
const app = createApp(RootComponent);
app.config.globalProperties.baseUrl='www.example.com'  
app.use(router).mount("#app");

You can then access this global property inside any child component like so:

<script>
   export default {
       data() {
        return {
            baseURL: this.baseURL
        }
       }
    }
</script>
<template> 
<div class="container-fluid">
    <div class="row text-center align-items-center height-150">
        <div class="col-xs-12 col-sm-12 col-lg-2">
            <div class="logo">
            <a href="/" title="">

                <h1>{{baseURL}}</h1> 

            </a>
            </div>
        </div>
     
    </div>
</div>
</template>

Answer №2

Often, when passing data from a parent to a child component is needed, props are utilized. However, consider a scenario where there is a complex component tree and a deeply nested component requires something from a distant ancestor component. Using only props would require passing the same prop through the entire parent chain. Instead, Props drilling can be used to reach deepchild components.

Props drilling involves utilizing provide and inject.

**PROVIDE** - A parent component acts as a provider of dependencies for all its descendants.

Example of Provide:

export default {
  provide: {
    message: 'hello!'
  }
}

Example of Inject:

export default {
  inject: ['message'],
  created() {
    console.log(this.message) // value injected
  }
}

Further information on this topic can be found here

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

Tips on implementing JSON data into select2 plugin

I have been trying to integrate the select2 plugin into my project. I followed a tutorial from this link, but unfortunately, it's not functioning properly for me. Here is the JSON output: [ {"ime":"BioPlex TM"}, {"ime":"Aegis sym agrilla"}, ...

Utilizing JQuery to request a file input and subsequently handle its processing

I am working towards creating a functionality where users can click a button, select a file, and have the program perform actions on that file, such as sending it through an AJAX request for processing. Currently, I have set up a hidden form along with a b ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Calculating the total sum in Vuejs when an event is triggered

I am faced with a situation where the price of a product is added to an existing total when a user increases the quantity. However, the problem lies in the fact that even if the user decreases the quantity, the price continues to increase. Solution html ...

JMeter recording displays a script alert error notification

After recording the JMeter script on blazemeter, it initially worked fine on the website. However, upon running the jmx file, I encountered an error message: "alert("Something went wrong. Please try again");window.history.back();" I&a ...

I am looking to use flexbox and Vue.js to organize my sent messages in blue on the right and received messages in yellow on the left. How can I achieve this grouping effectively?

I've successfully built a messenger system using Vue.js with a Laravel backend. My goal is to display messages from myself (Jim, the logged in user) on the right side in blue and messages from Debbie (the recipient) on the left side in yellow, similar ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

Jenkins encountered an issue where script execution was blocked on <URL> due to the document's frame being sandboxed without the 'allow-scripts' permission set

When using an iFrame in HTML, it's always best to remember to sandbox it and set the 'allow-scripts' permission to true. However, I'm facing an issue in my pure Angular JS application where there is no iFrame present. It runs smoothly ...

Revive your Chart JS visualization with interactive re-animation via onclick action!

I've been exploring Chart.js and trying to achieve something simple, but I'm having trouble. I just want the chart to re-animate when clicking on a button, but I can't seem to make it work. I attempted to attach chart.update to the onclick e ...

The component "react-native-snap-carousel" is having trouble displaying the card image

Recently, I started working with react native and encountered an issue while trying to implement the "react-native-snap-carousel". The carousel was functioning correctly with the data provided in the "carouselItems" array, but I faced difficulties with dis ...

Pass an array of links from the parent component to the child component in Vue in order to generate a dynamic

I am currently working on building a menu using vue.js. My setup includes 2 components - Navigation and NavLink. To populate the menu, I have created an array of links in the App.vue file and passed it as props to the Navigation component. Within the Navig ...

Choose the initial offspring from a shared category and assign a specific class identifier

I am trying to figure out how to apply the "active" class to the first tab-pane within each tab-content section in my HTML code. Here is an example of what I'm working with: <div class="tab-content"> <div class='tab-pane'>< ...

Guide to bringing in a variable from an external module

As a backend developer working on Node.JS code, I am trying to incorporate some constants from the @aws-sdk/signature-v4 module into my project. Specifically, I need to access AMZ_DATE_QUERY_PARAM as mentioned in the documentation. However, I am struggling ...

Implementing Java script for onkeypress event in a search bar that does not require a button

Currently utilizing this javascript to trigger an event on key press: function myFunction() { if (window.event || window.event.keyCode == 13) { changeSource(); } } function changeSource(){ document.getElementById("frame1").src="Log-In. ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...

Vue.js: Incorporating a client-side restful router using vue-router and a state manager

Trying to set up a client-side restful api with vue.js and vue-router where route params can be utilized to showcase a subset of a store's data into components. All the necessary data for the client is loaded into the store during initialization (not ...

Is the Child-Parent-Communication Method Lost?

I'm currently working on setting up communication between child and parent components in nuxtjs. Here is my child component: <div> <b-nav-item @click="clicked" :class="{active: active}">{{item.name}}</b ...

Guide to including configuration settings in locals for Sails.js

Currently working on a webapp with Sails.js, I am looking for ways to set up different configurations for development and production modes. Initially, I attempted to store the configuration key in config/local.js, but unfortunately, it did not yield the de ...

Sending numerous array values from datatables

I am currently working with datatables that allow for multiple selections. When I select 3 rows from top to bottom (as shown in this picture), the console.log returns this specific value for each row selected. The value that needs to be passed to the next ...