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

Incorporating Blank Class into HTML Tag with Modernizr

Currently, I am experimenting with Modernizr for the first time and facing some challenges in adding a class to the HTML tag as per the documentation. To check compatibility for the CSS Object Fit property, I used Modernizr's build feature to create ...

In need of assistance with Ember data! Struggling to deserialize JSON into model

Here is the technology stack I'm currently using: Ember 1.10.0 Ember Data 1.0.0-beta.15 Within my application, I have defined a model as shown below: //models//acceptedtask.js import DS from "ember-data"; export default DS.Model.extend({ userAg ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

Using React to create multiple modals and dynamically passing props

Each item in my list (ProjectActivityList) has an Edit button which, when clicked, should open a modal for editing that specific item. The modal requires an ID to identify the item being edited. var ProjectActivities = React.createClass({ onEditItem: ...

Using Typescript to define Vuex store types

Attempting to create a TypeScript-friendly Vuex store has been quite the challenge. Following instructions outlined here, I've encountered an issue where accessing this.$store from a component results in a type of Store<any>. I'm strugglin ...

How to efficiently utilize images with the VueJS Bootstrap carousel technique

My issue revolves around a specific requirement. Obtaining a list of images from the backend. The goal is to pass these image names to the carousel for image display. Showcased below is the code snippet I am working with. <template> <div cla ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Can a MS Teams Bot be triggered to show a botMessagePreview from a task or submit activity rather than a composeExtension or submitAction activity?

As I develop a messaging extension in Teams that utilizes task modules and sends adaptive cards, I am faced with the challenge of invoking the same task module from both a messaging extension command and a button on an adaptive card sent to the user. The ...

The clash between two jQuery plugins featuring identical function names

I have encountered a dilemma while working on a large website that includes two conflicting jQuery plugins for autocomplete functionality. The first plugin is jquery.autocomplete.js (not part of jQuery UI) which defines the autocomplete function like this ...

Custom HTML select element not triggering the onchange event

I found a code snippet on https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select that demonstrates a custom select input with an onchange event. However, I am facing an issue where the onchange event does not get triggered when I change th ...

Executing Function when Vue JS Input Loses Focus

Hey there, I have a quick question regarding Vue JS. So, on my website, I have a shopping cart feature where users can enter any quantity. The issue I'm facing is that every time a user types a digit in the input field, the save method gets triggered. ...

Tips for incorporating a hyperlink into a Vuikit table using Vue.js

I've exhausted all my options trying to make this work, and I'm on the verge of removing Vuikit... All I want is to pass dynamic data to the component, create a new HREF with that data, and have a clickable LINK text element displayed :) Here&a ...

Error: When attempting to utilize the Image-Slider, an issue arises with reading the property 'classList' which is undefined

I am currently in the process of developing a website using Strapi as my CMS and Next.js(React) for the frontend. The website features an image slider that includes images, headlines, and descriptions. However, I have encountered an issue where after spen ...

Fade or animate the opacity in jQuery to change the display type to something other than block

I am currently using display: table and display: table-cell to vertically align multiple divs. However, I have encountered an issue when animating the opacity with jQuery using either fadeTo() or fadeIn. The problem is that it always adds inline style di ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

Using an image as a button in Vue.js: A step-by-step guide

I'm currently working on creating a login button within a single-file-component using Vue.js in my Rails application with a Vue.js front-end. The purpose of this button is to redirect users to an external login page when clicked. I am wondering how I ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

javascript path as the first argument and callback as the last argument

Currently, I am in the process of creating a wrapper function for expressjs's app.get method. In these methods such as get, you can provide the path, some options, and then the callback. However, it is possible to omit the options and still have it w ...