Sharing VueJS router with child component

How do I pass the router to my child component?

This is my current router setup:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
export default function () {
const Router = new VueRouter({
    mode: 'history', 
    routes : [
      {
        path: '/',
        beforeEnter: ifAuthenticated,
        component: () => {
          return  import('./../container/Index.vue')
        }
      }, 
      {
        path: '/login',
        beforeEnter: ifNotAuthenticated,
        component: () => {
         return import('./../container/logn.vue')
        }
      }
    ],

  })

  return Router
}

The "/" (index.vue) route includes a Navbar component with a logout button that logs out the user and redirects them to the login page.

Here's an example of how I'm implementing this in my index.vue file:

<template>
  <q-layout>
    <Navbar :thisInfo="routerAndStore"/>
 </q-layout>
</template>

<script>
import Navbar from "./../components/navbar.vue";
export default {
  name: "PageIndex",
  components: {
    Navbar
  },
  data() {
    return {
      routerAndStore: this
    };
  }
};
</script>

In my navbar.vue component, I have the following code:

<template>
  <div class="nav-pages-main">
      <a @click="logoutUser">
        <h5>Logout</h5>
      </a>
  </div>
</template>

<script>
export default {
  name: "navbar",
  methods: {
    logoutUser: () => {
      return this.thisInfo.$store.dispatch("GOOGLE_PROFILE_LOGOUT").then(() => {
        this.$router.push("/login");
      });
    }
  },
  props: {
    thisInfo: {
      type: Object
    }
  }
};
</script>

Unfortunately, the 'this' object is coming out as undefined. Can someone help me understand how to correctly pass 'this' to a child component?

Answer №1

Make sure to check out the official Vue-Router documentation here

In their example, the main component (index.vue) receives a router as an argument and includes <router-view> in its template as a placeholder for the component that will be displayed based on the current route.

However, I noticed that you are using the router to render the main component in your code.

routes : [
  {
    path: '/',
    beforeEnter: ifAuthenticated,
    component: () => {
      return  import('./../container/Index.vue')
    }
  },
  ...
]

I recommend following the correct approach outlined in the documentation and let me know how it turns out.

Edit: Based on the App.vue file you provided (assuming it's the entry point of the app), make sure to provide the router to the App component.

<template>
    <div id="q-app"> <router-view/> </div>
</template>
<script>
    import router from '/path/to/your/router';

    export default { name: "App", router };
</script>
<style>
</style>

You can find the complete code example at Vue-Router example

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

Error occurred while trying to parse JSON due to an abrupt ending

While attempting to reinstall one of my old vue projects on my new computer (running Windows 10) using npm, I encountered the following error: npm ERR! Unexpected end of JSON input while parsing near '...n":"0.8.1","devDepend' ...

"Enhance your Vue 3 app with real-time data using GraphQL and Apollo - Learn how to automatically update queries when

I am eager to learn how to create Vue 3 Apollo applications using queries and mutations. I have experience with the react useQuery hook, which automatically re-renders the component when the cached data changes due to mutations. I have experimented with: ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Error: Module specifier "react-router-dom" could not be resolved. Relative references should start with either "/", "./", or "../"

I encountered an error message after executing the command npm run preview: Uncaught TypeError: Failed to resolve module specifier "react-router-dom". Relative references must start with either "/", "./", or "../". ...

Enable the event listener for the newly created element

I am attempting to attach an event listener to this HTML element that is being created with an API call handleProducts() function handleProducts() { var display = document.getElementById("display") var url = "http://127.0.0.1:800 ...

CKEditor not functioning properly when generated using AJAX and PHP in JavaScript file

I am facing an issue where I am using PHP and AJAX to generate a CKEditor textarea. The CKEditor JavaScript files are included in the main HTML file, and the PHP and AJAX functionalities are working correctly. However, when the form is displayed, the CKEdi ...

What sets apart the browser/tab close event from the refresh event?

Can you help me understand the difference between a browser/tab close event and a refresh event? I've been researching this on Stack Overflow, but I'm still having trouble with it. My goal is to be able to log out a user through a server call whe ...

React-router can manage non-matching paths by utilizing a basic JavaScript router configuration

Is there a way to manage non-matching paths using plain JavaScript in React router configuration? const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: App, childRoutes: [ requir ...

When clicking on an item in the wishlist, only the text for that specific item should change,

Hi all, I'm in need of some assistance. I have successfully created a wishlist toggle where clicking on the heart icon changes it from an outline to solid. However, my issue lies in changing the tooltip text from "add to wish list" to "added to wish l ...

How can I modify the color in vue-google-chart when a filter option is selected?

I created a stack column chart with a filter that changes the color to blue when selected. Here is my Vue app: https://codesandbox.io/s/vue-dashboard-chart-6lvx4?file=/src/components/Dashboard.vue I expected the selected color to match the color in the ...

What is the best way to dynamically insert an object into a field name in react-final-form?

When using the react-final-form component, you can expect the following result: <Field name="answers[0].name" component="input" type="radio" value="0" /> { answers: [ { name: 'value' } ] ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

avoiding the duplication of effects on an object when new objects are added via ajax

Currently, I am facing a minor issue with an application that I am working on. The problem arises on a particular page where the user can edit a document by dragging modules onto the canvas area. Upon loading the page, JavaScript causes the modules to be ...

What is the best way to conceal two Bootstrap divs that should not both be visible at the same time?

I am working with two different types of charts: an Emotion chart and a Polarity chart. To control the visibility of these charts, I have implemented two buttons, one for each chart. The functionality is such that when the first button is clicked, only the ...

What can be done to enhance this particular element?

I've created a Component that uses a 3rd party joke API to fetch jokes with a specific category upon page load. The component also includes a refresh button for fetching new jokes. export default function Jokes() { const { cat } = useParams(); const [ ...

What is the best way to implement multilanguage support in nodejs without relying on cookies or external modules?

Currently, I am in the process of transitioning all my projects to node.js in order to enhance my JavaScript skills. Using Node.js along with the Express module, one of my clients who runs a translation company has requested that I incorporate two language ...

Can you explain the concept of an anonymous block in JavaScript ES6 to me?

Recently, I came across an article on pragmatists which discussed some interesting ES6 features. However, one concept that caught my attention was the use of an anonymous block within a function. function f() { var x = 1 let y = 2 const z = 3 { ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

How to interact with AngularJS drop-down menus using Selenium in Python?

I have been working on scraping a website to create an account. Here is the specific URL: Upon visiting the site, you need to click on "Dont have an account yet?" and then click "Agree" on the following page. Subsequently, there are security questions th ...

I am looking to sort through the data based on the courseCode, but I can't seem to find a way to do it

Here is the JSON data after converting it with res.json() I attempted to filter it based on course code, let's say the code is: 301. I am confused about how to achieve this using JavaScript because of the nested structure. Here is the code snippet I ...