Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the buttons for protected sections. However, I'm facing an issue after submitting the login on my login component. I am unsure how to trigger the re-rendering of the navigation bar component to show the correct buttons.

I'm considering whether I should use a global variable in my main component or if I need to emit an event from the child to the parent, then emit another from the main component to the navigation bar. There may be a simpler solution that I haven't considered yet.

If more information is needed, please feel free to ask. Thank you in advance.

Answer №1

One of the key challenges I encountered was establishing communication between components within the same hierarchy. To address this issue, I opted for an Event Bus approach outlined in the Vue.js documentation:

https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

To implement this, I created a new instance of Vue named EventBus:

// EventBus.js
import Vue from 'vue'
export default new Vue()

This EventBus was then globally included in my main Vue instance:

// main.js
import EventBus from './EventBus'
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

Vue.prototype.$bus = EventBus

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
})

By using this setup, I could emit events within components and listen for them across other components in the same hierarchy, like demonstrated below:

// Login.Vue
import axios from 'axios'
export default {
     name: 'login',
     data () {
         let data = {
             form: {
                  email: '',
                  password: ''
             }
         }
         return data
     },
    methods: {
        login () {
            axios.post('http://rea.app/login', this.form)
            .then(response => {
                let responseData = response.data.data
                this.$localStorage.set('access_token', responseData.token)
                this.$bus.$emit('logged', 'User logged')
                this.$router.push('/')
            })
            .catch(error => {
                if (error.response) {
                    console.log(error.response.data)
                    console.log(error.response.status)
                    console.log(error.response.headers)
                }
            })
        }
    }
}

In another component, listening to these emitted events can be achieved by setting up a listener in the create method:

// NavBar.js
export default {
     template: '<Navigation/>',
     name: 'navigation',
     data () {
         return {
             isLogged: this.checkIfIsLogged()
         }
     },
     created () {
         this.$bus.$on('logged', () => {
             this.isLogged = this.checkIfIsLogged()
         })
     }
 }

I believe this can serve as a helpful reference for similar scenarios.

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

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Struggling to make the JavaScript addition operator function properly

I have a button that I want to increase the data attribute by 5 every time it is clicked. However, I am struggling to achieve this and have tried multiple approaches without success. var i = 5; $(this).attr('data-count', ++i); Unfortunately, th ...

`How to implement text that changes dynamically within images using HTML and PHP`

I'm working on a PHP website with Codeigniter and I have a requirement to insert HTML text into an image fetched from a database. The content of the text will vary based on different profiles. Below is the image: The text "$40" needs to be dynamic. H ...

Tips for navigating the world of hybrid web applications that combine elements of both traditional multi-page applications and single-page

What are some best practices for developing a multi-page application using modern JavaScript frameworks? Multi-page Application In a multi-page application, we utilize multiple templates with "template syntax" to retrieve backend data and handle AJAX (if ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Having trouble resolving a missing dependency warning with the useEffect React Hook in my Next.js app. Any tips on how to fix this

Currently, I'm facing the following warning: Warning: React Hook useEffect has a missing dependency: 'router'. Either include it or remove the dependency array Here is the code snippet from _app.js that seems to be causing this issue: cons ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

Transfer the HTML5 FullScreen (MAP) feature onto a separate display

I'm trying to integrate a leaflet map into my AngularJS Application, but I've hit a roadblock. My goal is to move the Fullscreen feature of the Map to a second screen (if one is available), allowing users to interact with the application on the ...

Exploring file writing using Node Webkit and JavaScript

When developing my app, I encountered an issue with the 'fs' module not functioning as expected. Despite the code being written to write a file, nothing happens when the app is launched. However, if I start the app using the following command: $ ...

Disabling caching in bootstrap tabs for loading ajax content

My goal is to make bootstrap tabs load content through ajax queries. While this process is straightforward with Jquery tabs, which default to loading content via ajax query, it seems to be a different case for bootstrap. As such, I have come across the fo ...

Using VueJS and Jest: A guide to testing and spying on methods triggered by watchers

Here is a snippet of code showcasing VueJs components. It includes a watcher and a method implementation. computed: { ...mapGetters({ resourceLinks: `tools/${storeGetters.resourceLinks}`, }), }, m ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...

Incorporating an AngularJs App into Joomla: A Step-by-

As someone who is currently learning both Angular and Joomla, I am curious about the possibility of integrating an Angular JS Application within Joomla. While Joomla is known for its ease in creating articles and managing content through the admin panel, i ...

An error was encountered stating "TypeError: Unable to call function on undefined object while attempting to utilize a JSON object

My current setup involves using D3js with MongoDB and AngularJS to showcase my data. Everything works smoothly until I decide to give my JSON array a name. Suddenly, Angular starts throwing errors at me and I'm left confused as to why. Here is the or ...

Upload a JSON file to a server using a JavaScript app

I am in the process of creating a basic JavaScript application that allows users to annotate images stored on their machine and save these annotations as a JSON file. This application is lightweight and straightforward, not requiring an app server. Howeve ...

Is there a way for me to gain entry to this array in vuejs?

Can anyone help me with accessing the objects in this array? I am using laravel, inertiajs, and vuejs. I am passing a variable from a laravel controller to a vuejs component with inertia.js. https://i.stack.imgur.com/p7yjL.png https://i.stack.imgur.com/y ...

JavaScript - I have a variable trapped inside a function and I'm struggling to retrieve it

Is it possible that I'm missing something obvious here? I am really struggling to pass the 'body' variable out of this nested function. function retrieveFacebookInfo(userID) { request({ "url": "https://graph.facebook.com/v2.6/" + ...

The callback function does not get invoked when using JSONP

Learning jsonP has been a challenge for me as I am relatively new to it. I have done my research by reading various articles but when trying out a simple example, the callback function fails to execute. Surprisingly, there are no errors or exceptions logge ...

Using Javascript to create a new regular expression, we can now read patterns in from

I am currently working on developing a bbcode filtering solution that is compatible with both PHP and JavaScript. Primarily focusing on the JavaScript aspect at the moment, I have encountered an issue with the new RegExp constructor not recognizing pattern ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...