How can I conceal login and register router-links in the Vue + Laravel SPA project navbar immediately after a user logs in?

Currently, I am working on my Bachelor's degree project and have encountered a specific issue. While the login, register, and logout functions all seem to be working well, there is an inconsistency with the navigation bar not automatically switching between the login/register options and the logout option.

<template>
    <header>
        <nav>
            <div class="container">
                <router-link to="/" class="routerLink"><h1>Proiect Licenta</h1></router-link>

                <div class="menu">
                    <router-link to="/buy">Buy Crypto</router-link>
                    <router-link to="/market">Market</router-link>
                    <router-link to="/about">About</router-link>
                    <router-link to="/contact">Contact</router-link>
                    <router-link v-if="!checkLogged" to="/signup">Signup</router-link>
                    <router-link v-if="!checkLogged" to="/login">Login</router-link>
                    <base-button mode="flat" v-if="checkLogged" @click="logout">Logout</base-button>
                </div>
            </div>
        </nav>
    </header>
</template>

<script>
import User from '../../helpers/User.js';

export default {
    data() {
        return {
        }
    },
    methods: {
        logout() {
            User.logOut()

            Toast.fire({
                icon: 'success',
                title: 'Logout successfully'
            });

            this.$router.push({ name: 'homePage' });
        },
    },
    computed: {
        checkLogged() {
            if(User.loggedIn()) {
                return true;
            }
            return false;
        },
    },
}
</script>

User.js:

    hasToken() {
        const storeToken = localStorage.getItem('token');

        if(storeToken) {
            return true;
        }
        return false;
    }

    loggedIn() {
        return this.hasToken();
    }

    logOut() {
       localStorage.removeItem('token');
       localStorage.removeItem('user');
    }

The navigation bar is integrated into the app.vue component, leading me to believe that it remains static unless the page is refreshed. How can I achieve an immediate switch between the login/register links and the logout option after successful login and redirection to the main page? Any additional details needed will be provided promptly. Thank you.

Answer №1

Since your code deals with user login and logout, particularly involving backend processes related to the app, I decided to simulate this by clicking on the login and logout buttons. This action triggers the functions in the "user.js" file without actually going through the login or registration process. Here's a snippet from the "user.js" code:

user.js:

export default {
    hasToken() {
        const storeToken = localStorage.getItem('token');

        if (storeToken) {
            return true;
        }
        return false;
    },

    loggedIn() {
        return this.hasToken();
    },

    logOut() {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
    },

    /* This method simulates the user login process. Keep in mind that you may set the token elsewhere in your code. */
    login() {
        console.log("logged in");
        localStorage.setItem("token", "my value");
    }
}

Additionally, here is the navigation code that can be imported into your App.vue.

TheNavigation.vue:

<template>
  <header>
    <nav>
      <div class="container">
        <router-link to="/" class="routerLink"><h1>Project Title</h1></router-link>

        <div class="menu">
          <router-link to="/buy">Buy Crypto</router-link>
          <router-link to="/market">Market</router-link>
          <router-link to="/about">About</router-link>
          <router-link to="/contact">Contact</router-link>
          <router-link v-if="!switchData" to="/signup">Signup</router-link>
          <router-link @click.native="loginMethod" v-if="!switchData" to="/login">Login</router-link>
          <button mode="flat" v-if="switchData" @click="logout">Logout</button>
        </div>
      </div>
    </nav>
  </header>
</template>

<script>
/* Import user.js from your directory */
import User from '../helper/user.js';

export default {
  name: "TheNavigation",
  data() {
    return {
      switchData: false
    }
  },
  methods: {
    logout() {
      User.logOut()
      this.checkLogged();
    },
    checkLogged() {
      if(User.loggedIn()) {
        this.switchData = true;
      } else {
        this.switchData = false;
      }
    },
    loginMethod() {
      User.login();
      this.checkLogged();
    }
  }
}
</script>

A significant change I made was converting checkLogged() from a computed property to a Vue method and calling it after any login or logout operation. This way, Vue consistently checks the local storage and adjusts button states accordingly. You can also test this functionality in the provided CodeSandbox link.

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

Creating fluid motion with a bezier curve in ThreeJS

I am looking to animate a bezier curve in ThreeJS with updating start, end, and control points. Eventually, I will have multiple curves animating simultaneously. What is the most efficient approach to achieve this? When running the code snippet below, you ...

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

Discover the paths to locate all keys within an object that correspond to a specified string

I need help creating a function in plain JavaScript that can find all paths to keys with a specific name in an object. The object may have repeated key names at different depths. Here is an example: const obj = { stuff: { A: 'text' ...

Having trouble with installing NPM and ng commands, neither of them is working. I may have to uninstall everything and begin from scratch

Learning Angular and how to use the terminal is all new to me. I recently installed NPM and attempted to use ng serve, but encountered a series of issues. At this point, I am considering completely uninstalling everything so I can start fresh. I've d ...

How to manually add the $store parameter to a dynamically created Vue component that is missing it during creation

I'm a newcomer to the world of Vue/Nuxt and I've encountered an issue while attempting to dynamically generate a Vue component on button click using the following code: async addComponent(componentsItem) { var ComponentClass = Vue.component(&a ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

Utilizing the power of JavaScript within HTML to remove elements upon being clicked

Seeking help again for the page I'm building where I keep encountering errors. As a beginner, I find myself puzzled and in need of assistance. My task is to utilize a for loop to iterate over the images and attach an event listener to each one so that ...

Various ways to declare functions in JavaScript

1)Function declaration with variable name: var x = function (a, b) {return a * b}; 2)Another type of function in JavaScript within Angular1: var method = { add_category: function(data, success, failure) { $upload.upload({ url: b ...

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...

What is the best way to limit the number of items displayed in a Bootstrap card?

While using bootstrap cards to display content, I encountered an issue when integrating it with the backend for looping. The items were continuously added to the right side instead of being set in columns of 3 and continuing straight down. It should look ...

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

Allow the NodeJS application to conduct self-updates using the NPM package manager

Hello, I'm currently exploring ways to add unique functionality to my NodeJS application, but I'm encountering some challenges. What I aim to achieve is as follows: I am interested in implementing a server code update feature from the client si ...

Building an anchor tag that employs the HTTP DELETE method within an Express.js app

Recently, I delved into using express.js with handlebars.js as my template engine. One task I wanted to tackle was creating a delete link that followed RESTful principles and used the HTTP DELETE verb instead of GET. After some trial and error, I discover ...

Preventing Browser Back Button Functionality in Angular 2

I'm currently working on an Angular 2 website and wondering if there is a way to either disable or trigger the browser's back button using Angular 2. Any insights would be greatly appreciated! ...

Issue with Express.js: "opencv" module not found within a Docker container

Currently, I am in the process of setting up the OpenCV bindings for NODE to enable AI functionality on my express server. For this purpose, I am utilizing the Peter Braden Library - https://github.com/peterbraden/node-opencv. However, I am encountering a ...

Stop button from being clicked inside a div when mouse hovers over it

I am facing an issue with a div containing a mouseenter event and a button inside it with a click event. The concept is that when the user hovers over the div triggering the mouseenter event, the div becomes "active", allowing the button to be visible and ...

Having trouble getting your custom Angular directive to function properly with dynamically changing images?

Currently in the process of developing a custom directive for AngularJs that involves an image rotator based on a Jquery Plugin I created, you can check it out here Below is the code snippet for my directive: .directive('imageRotator', function ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

How to use puppeteer to extract images from HTML that have alt attributes

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center"><!-- Start Product Photo --><div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1">&l ...