skip to Main Content

I’m new to Vue.js and can’t seem to get how an event is passed from a component outside of the router-view to App.vue. I’m currently using the below code in the App.vue

<template>
    <div>
        <NavBar :userId="userId" :loggedIn="isLoggedIn" />
        <router-view :userId="userId"
            @user-logged-in="getLoggedInUserInfo" 
            @user-logged-out="getLoggedOutUserInfo">
        </router-view>
    </div>
</template>

<script>
import NavBar from '@/components/NavBar.vue';

export default {
    name: 'App',
    components: {
        NavBar,
    },
    data: function () {
        return {
          userId: null,
          isLoggedIn: false,
        }
    },    
    methods: {
        getLoggedInUserInfo: function(data) {
            this.userId = data.user.userId;
            this.isLoggedIn = true;
        },

        getLoggedOutUserInfo: function() {
            this.userId = '';
            this.isLoggedIn = false;
        }
    }
}
</script>

I am using a page(component) Login.vue to enter credentials for logging in to the application. This page is part of the router-view. I can trigger the user-logged-in event from the Login.vue page and it works as expected when a user logs in.

this.$emit("user-logged-in", data);

However, when the user logs out, I want to receive some information in the NavBar component, so that I can re-render the NavBar menu items. The logout button stays in the Navbar component.

I tried to emit the logout to the App.vue from the NavBar.vue as shown and it does not work:

this.$emit("user-logged-out");

Any help is much appreciated!

2

Answers


  1. i suggest you to make an eventBus

    import Vue from 'vue';
    export const EventBus = new Vue();
    

    then trigger events from navbar component
    and listen to the events using event bus

    or
    try to use "mitt" from npm and to make eventBus and use it across the application

    import mitt from ‘mitt’
    const emitter = mitt()
    export default emitter

    Login or Signup to reply.
  2. As the logout button is present in the NavBar, but you are listening for the event in router-view, you can simply emit the event from NavBar and handle it App file.

    <NavBar :userId="userId" :loggedIn="isLoggedIn" @user-logged-out="getLoggedOutUserInfo">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search