Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh?

This is what my homepage looks like:

<template id="" v-if="page.homepage">
      <div class="container ">
       <h1> Homepage </h1>
  </div>
</template> 

This is my login form:

  <template id="" v-if="page.login">
              <div class="container ">
               <h1> Login </h1>
          </div>
        </template> 

Here is the method I'm using:

loginButton(){
   this.page.homepage = false
   this.page.login = true
}

I've been struggling with this issue for quite some time now, any help would be greatly appreciated.

Answer №1

To enhance your Vue.js application's navigation, you can implement router guards with vue-router.

An example of using beforeEach for navigation control:

router.beforeEach((to, from, next) => {
  const authenticated = !!localStorage.getItem('token')

  if (['login'].includes(to.name) && authenticated) {
    next({ path: 'home' })
  } else if (['home'].includes(to.name) && !authenticated) {
    next({ path: '/login' })
  } else {
    next()
  }

})

Note: The above example demonstrates the use of a stored token to determine whether a user is logged in or not.

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

Is there a way to ensure that the div of my template spans 100% in width and height?

I'm attempting to make my div 100% in size but I am having trouble achieving it. Here is my code: <template> <div> <Navbar/> <Calendar/> </div> </template> <script setup> import Calendar from &apos ...

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

What is the best method for applying an active class to a particular element?

I have the following methods: methods: { replyBox: function(event){ event.preventDefault(); this.isActive = !this.isActive; ); }, In my view, I have this: <div class="comment_list" v-for="comme ...

Drawing intersecting lines on a javascript canvas and clearing them using the lineto method

I am working with a canvas where lines are drawn based on mouse movement. I am trying to achieve the effect of the line only lasting for a few seconds before disappearing, similar to swirling a ribbon with a set length. I have been using lineTo to draw the ...

Sending Django Variable With Javascript

As a newcomer to Javascript, I am grappling with retrieving the value of a variable from my HTML form. My current code seems to be somewhat functional - I added an alert to test the logic and found that the else statement is working fine. However, I'm ...

Deleting an element from a reference array in Mongoose

In my code, I have a User model that contains an array of references to other users: friends : [ { type: Schema.Types.ObjectId, ref: 'User' } ] I am currently struggling with removing an item from this list. Here is what I have attempt ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

``What is the best approach for specifying property types when passing props to grandchildren within a Vue.js component hierarchy

I have a Vue component named foo embedded in my HTML, and I am passing a parameter to it as shown below: <foo some="Some String"></foo> Within the foo component, I define the property type and default value in the following manner: export d ...

What is the process for a server to transmit a JWT token to the browser?

Here is an example response sent to the browser: HTTP / 1.1 200 OK Content - Type: application / json Cache - Control : no - store Pragma : no - cache { "access_token":"MTQ0NjJkZmQ5OTM2NDE1Z ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Using JavaScript and the Firefox browser, learn how to easily highlight an element with Selenium-WebDriver

I am struggling with creating a valid function to highlight specific elements on a webpage. As a beginner in coding, I suspect that the issue may either be related to my environment setup or a lack of knowledge about JavaScript/Selenium features. I am wri ...

What is the best way to incorporate lottiefiles for a loading animation on a Next.js project's landing

Is there a way to incorporate the use of lottie in a Next.js project (App Structure) in order to load an animated logo seamlessly? I attempted to include "use client" without success, and also tried importing Lottie from react-lottie as a dynamic import. ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

Looking to display a gif when a user clicks a button

I need help with making a spinner gif hidden in Unbounce and then show when the user clicks a button. The button is labeled #lp-pom-button-279 and the image is labeled #lp-pom-image-288 My attempts to use JS and CSS have resulted in the gif being either a ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

What is the best way to handle waiting for a React context provider that requires time to initialize the value it provides?

In my Next.js application, I have a global context that takes five seconds to compute the value provided: import React, { useContext, useEffect, useState } from 'react'; const GlobalContext = React.createContext(); export const GlobalContextPro ...

Building a framework for combined frontend and backend plugins using Vue and Express

Currently, I am facing a challenge with my repository which contains a Vue CLI-generated frontend application and an Express backend application. The setup involves a standard Vue CLI app with a top-level backend src folder. The Express app defines various ...