unanticipated redirection with Vue router

Here is the routing code snippet:

// exporting for component use
export var router = new VueRouter();

// defining routes
router.map({
    'home': {
        component: Home,
        auth: true
    },
    'login': {
        component: Login,
        auth: false
    }
});

// redirecting to fallback route
router.redirect({
    '*': 'home'
});

router.beforeEach(function (transition) {
    console.log("here!");
    console.log("beforeeach auth.user.authenticated: "+auth.user.authenticated)
    if (transition.to.auth && !auth.user.authenticated) {
        // redirection for authentication check
        transition.redirect('login');
    } else {
        transition.next();
    }
});
// starting the app at element with id 'app'
router.start(App, '#app');

Now examining the auth/index.js

export default {
    user: {
        authenticated: false
    },

    login: function(context, creds, redirect) {
        this.user.authenticated=true;
        console.log("logged in!");
        router.go('/home');
    },

    logout: function() {
        this.user.authenticated=false;
        console.log("logout");
        router.go('/login');
    }
}

A snippet of my Nav.vue file:

<template>
    <div class="top-nav-bar" v-if="user.authenticated">
     // other code here....
                   <ul class="notification user-drop-down">
                    <li><a href="#" @click="logout()">Logout</a></li>
                   </ul>
     // other code here ...
    </div>
</template>

<script>
    import auth from '../services/auth';

    export default {
        data: function () {
            return {
                user: auth.user
            }
        },
        methods: {
            logout: function () {
                auth.logout();
            }
        }
    }
</script>

Upon clicking the logout button, it redirects to localhost:8080/#!/home However, the auth.logout() function contains router.go('/login'), which should redirect to the login Controller!

If I manually enter localhost:8080/!#/home in the browser, it correctly redirects to the /login page. So why does the logout button remain at /home without any errors displayed?

UPDATE:

The versions being used are vue 1.0.7 and vue-router 0.7.5

Answer №2

The reason for the error I encountered was due to my utilization of an <a> element.

<li><a href="#" @click="logout()">Logout</a></li>

Instead of triggering the @click event, it was navigating to the # URL, leading to the fallback route. To address this issue, I incorporated @click.prevent to prevent the default behavior of the anchor tag:

<li><a href="#" @click.prevent="logout()">Logout</a></li>

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

Nested promise not being waited for

As someone new to all things asynchronous, I am currently facing a challenge. I want to ensure that a file exists before updating it, creating the file if necessary. However, I am struggling to figure out how to achieve this. I am aware of the option to u ...

Tips for updating the corresponding nav link in CSS when transitioning between pages

In order to highlight the current page in the navigation menu, one method is to use an active attribute on the nav-link of the respective page: <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link navLink ...

Utilizing the 'input' method to modify the key of an array object within specified elements in a Vue.js application

i am looking to implement an input field that can be used to edit the title of the currently selected element component (the selection is made by clicking). The challenge here is to have a single input that works for each individually selected element. I h ...

Navigate through stunning visuals using Bokeh Slider with Python callback functionality

After being inspired by this particular example from the Bokeh gallery, I decided to try implementing a slider to navigate through a vast amount of collected data, essentially creating a time-lapse of biological data. Instead of opting for a custom JavaS ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

I am facing an issue with Lotties having a black background in my NextJS project. Is there a way to make them transparent

I am facing an issue with my LottieFiles (JSON) displaying a black background when imported into my NextJS project. Despite trying to set background='transparent' on both the Player and parent div, the problem persists. I made sure to export my ...

Issues with inputmask functionality in Vue.js when using jQuery are causing it to

I'm currently facing an issue while attempting to implement the inputmask plugin as a Vue.js directive. The error message I'm encountering reads: $(...).inputmask is not a function Once I resolve this error, I will need the input value to be sy ...

Comparing ASP.NET Core and Node.js: A Closer Look at Their Similar

After working with Node.js for some time, I have gained a deep understanding of how it operates internally, including the event loop and other aspects. However, I can't help but notice that ASP.NET Core bears a striking resemblance to Node.js. ASP.NE ...

Encountered a glitch while trying to install React JS using npx create-react-app xyz

After entering the command in the terminal, I encountered an error stating: npm Err! code-ENOENT npm Err! syscall lstat npm Err! path Interestingly, this same command worked perfectly on my instructor's laptops. For reference, I have attached a snaps ...

creating sleek animations with Pixi.js for circular shapes

Is it possible to create smooth animations on circles or sprites similar to D3.js hits in Leaflet? https://drive.google.com/file/d/10d5L_zR-MyQf1H9CLDg1wKcvnPQd5mvW/view?usp=sharing While D3 works well with circles, the browser freezes. I am new to Pixi. ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

Tips for disentangling code from types in Typescript

Instead of intertwining code and types like the example below: const compar8 : boolean | error = (action: string, n: number) => { switch(action) { case 'greater': return n > 8; case 'less': ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

How can you effectively utilize Selenium to web scrape a webpage featuring collapsible fields?

Have you checked out this website - ? I'm currently working on extracting fixture data from it, such as competition names, team names, and dates. Although I have a scraping solution in place, the challenge lies in dealing with collapsible competition ...

What is the best way to connect the imagemap shape with the checkbox?

I need assistance with synchronizing an imagemap collection of shapes and checkboxes. How can I ensure that clicking on a shape selects the corresponding checkbox, and vice versa? Imagemap: <div class="map_container"> <%= image_tag("maps/main ...

What's the best way to navigate across by simply pressing a button located nearby?

Hey there! I'm new to JavaScript and I'm working on a shopping list page for practice. In my code, I can add new items to the list, but what I really want is to be able to cross out an item when I click the "Done" button next to it, and then uncr ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...

Determine in JavaScript whether a character is 32-bit or not

Is there a way to determine if a specific character is 32 bits using JavaScript? I attempted to use charCodeAt() but it was unsuccessful for identifying 32-bit characters. Any guidance or assistance on this matter would be greatly valued. ...