Having difficulty accessing the $root variable in Vue.js

Within my app, there is a root page featuring a Navbar component. I am attempting to access a variable called currentRoute from this Navbar component. The code in my index.js file where I have defined currentRoute is as follows:

import Vue from 'vue';
import routes from './routes';

var app = new Vue({
    el: '#app',
    data: {
        currentRoute: window.location.pathname,
    },
    computed: {
        ViewComponent () {
            return routes[this.currentRoute] || routes.NotFound;
        }
    },
    render (h) {
        return h(this.ViewComponent)
    }
});

window.addEventListener('popstate', () => {
    app.currentRoute = window.location.pathname;
});

In addition, I have a home.vue file which serves as the default route and includes a component named Navbar. In this component, I am trying to access currentRoute. Here is what the code looks like:

<template lang="jade">
.navbar
    .row
        .col.text-center
            a.post-outline.navbar--icon(href='/new-post', @click="newPost")
        .col.text-center
            i.email-outline.navbar--icon
        .col.text-center
            i.person-outline.navbar--icon
</template>

<script>
import routes from '../../routes';
export default {
    props: {
        href: String,
        required: true
    },
    computed: {
        isActive () {
            return this.href === this.$root.currentRoute
        }
    },
    methods: {
        newPost: event => {
            event.preventDefault();

            this.$root.currentRoute = this.href;

            window.history.pushState(
              null,
              routes[this.href],
              this.href
            )
        },
    },
}
</script>

The contents of my routes.js file are as follows:

import NotFound from './pages/404.vue';
import Home from './pages/home.vue';
const NewPost = { template: '<p>new post page</p>' }

export default {
    '/': Home,
    '/new-post': NewPost
}

Despite everything appearing to be in order, I find that this.$root remains undefined. Where could I be making an error?

Answer №1

The function newPost() in your codebase utilizes the ES6/2015 arrow function syntax (() => {}), which links this to the parent context. In this scenario, the parent context refers to the module rather than the Vue instance, causing it to lack access to $root.

To address this issue, you have two options:

Declare the function using traditional syntax:
function newPost(event) { }

Alternatively, you can utilize the ES6/2015 shorthand:

newPost(event) { }

Answer №2

When working with vue.js, data flows from parent components to children components through props. The important thing to note is that it is passed by reference, meaning any changes made to the data in the child component will directly impact the state of the parent component.

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

Don't forget to retain filled values when navigating with Vue Router

I have a quick and straightforward question that I would appreciate your input on. In my Vue router setup, I have added navigation tabs for "Home" and "Configuration." On the "Configuration" page, I input some data without saving it, then navigate back t ...

Issue encountered with adjusting the scale of vUv in a custom shader for three.js: as the multiplying factor decreases, the painted result grows larger in size

Currently, I am experimenting with a custom shader in three.js to create an animated and expanding texture. However, I have encountered an issue where multiplying vUv by a certain number results in unexpected behavior. Strangely, when the number is increas ...

What is the purpose of the 'new' keyword in JavaScript?

After years of using JavaScript like a semi-imperative version of Lisp, I am still confused about how constructors actually work in the language. I would appreciate some insight into how objects are meant to function in JavaScript. Consider this code snip ...

Color-Thief Node plugin reported an issue: "The provided image has not finished loading."

While working in Node/Express, I attempted to utilize the npm package color-thief to extract the dominant color from an image. Unfortunately, it failed with the error message stating that the "image given has not completed loading". The intriguing part is ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Can you explain how TypeScript determines the intrinsic attributes in React?

Many questions on SO seem to be talking about errors related to matching with type 'IntrinsicAttributes' For instance, when trying to pass a prop like <Greet foo="hello" /> to a component without defining it in the component prop ...

Send an AJAX request to redirect to a different page on a PHP server

After collecting data from JavaScript, my page transfers it to PHP and then MySQL. The issue arises when I want the page to redirect to different pages based on the database content. I attempted to use the header function, but it only displayed the entire ...

Measuring Load Time Percentage in AngularJS Using $http Requests

I am currently utilizing Angular with my Rails application. I have a sample app and I am interested in displaying the response time required to load a response in Angular. For example, When loading a response of an array containing 100,000 elements, I w ...

Calling another function within a loop in Vuejs causes an error

I am working with a code sample that contains data for cities including latitude and longitude values. Here is the code snippet: ... methods: { mapDrag: function () { let lat = 100; let lng = 200; this.cities.forEach(fu ...

Develop a real-time preview of the form inputs

While working on a multistep form, I am exploring the idea of creating a live preview that shows values entered into different input fields, text areas, and radio buttons. Currently, I have successfully built the form and made some progress using the foll ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

What is the process for adding new data to a data source without overwriting existing information?

I need assistance with a react native app I am developing. I am currently facing an issue where the data received from a fetch request needs to be displayed in a list view. However, each time new data is fetched, it overwrites the previously received data ...

When I declare 'i' above the for loop, the output shows as 3 3 3, while declaring 'i' inside the for loop results in an output of 1 2 3

Setting up the variable i before the for loop will result in the output being 3 3 3. let i; for (i = 0; i < 3; i++) { const log = () => { console.log(i); } setTimeout(log, 100); } //Output 3 3 3 If i is declared within the for loop, the o ...

What is the best way to transfer a map from Java to JavaScript?

I have a dropdown menu with an information tooltip icon next to it. When the user changes the selection in the dropdown and hovers over the info icon, a description for the selected item should appear as shown in the image: https://i.sstatic.net/K1S64.jpg ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Is there a way to effortlessly upload numerous files in one go when browsing with jquery or JavaScript?

Currently working on a web application and looking to enable multiple file upload functionality within a single browse session, as opposed to selecting one file at a time. The goal is for users to be able to easily select multiple files with just one clic ...

Tips for effectively sorting data in the 'model' using StrongLoopIf you want assistance in filtering data in the

I'm currently attempting to connect table ABC with XYZ, and filter the data from the linked table 'xyz' using the Strongloop framework. Here is my code: return ABC.find({filter:{ where: {abcPropertyName: {neq: '1 ...

Execute the "organizeImports" trigger through the terminal in TypeScript

One feature of VSCode is its editor capability to organize and clean imports in javascript and typescript files upon saving ( "source.organizeImports": true ). Inquiry Is there a way to trigger this action on a file using the command line? Something alo ...

The order in which JavaScript is being executed is being reversed

function checkForDuplicate(center, email) { $.ajax({ type: "POST", url: "../staff/staffDA.php", data: "funId=-4&center=" + center + "&email=" + email, success: function (data) { if (data.split('| ...

Guide on using jQuery to incrementally cycle through an array using a button

I am facing an issue with iterating through an array of objects using a button. The iteration is skipping 2 on each click instead of moving to the very next record. Can someone help me troubleshoot this problem? Or suggest a better approach to iterate thro ...