Is there an issue with Vue-router 2 where it changes the route but fails to update the view

I am currently facing an issue with the login functionality on a website that utilizes:

  • Vue.js v2.0.3
  • vue-router v2.0.1
  • vuex v0.8.2

In routes.js, there is a basic interceptor setup

router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!router.app.auth.isUserLoggedIn) {
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    } else {
        next()
    }
} else {
    next() // make sure to always call next()!
}

And in login.vue, which handles the logic of the login page after successful login using the Google API, I perform the following:

this.login(userData).then( 
    () => this.$router.push(this.redirectToAfterLogin), // Login success
    () => {} // Login failed
)


mounted: function(){
if (this.auth.isUserLoggedIn){
            // Let's just redirect to the main page
            this.$router.push(this.redirectToAfterLogins)
        }else{
            Vue.nextTick(() => {
                this.loadGooglePlatform()
            })}}


computed: {
        redirectToAfterLogin: function() {
            if (this.$route.query.redirect){
                return this.$route.query.redirect
            }else{
                return '/'
            }
        }
    }

router.js

var VueRouter = require('vue-router')

// Router setup
export const router = new VueRouter({
    linkActiveClass: "is-active",
    mode: 'history',
    saveScrollPosition: true,
    routes: [
        { path: '', name: 'root', redirect: '/home' },
        { path: '/login', name: 'login', meta: { loadingNotRequired: true }, component: require('./pages/login.vue') },
        { path: '/logout', name: 'logout', meta: { loadingNotRequired: true }, component: require('./pages/logout.vue') },
        { path: '/home', name: 'home', title: 'Home', redirect: '/home/random', component: require('./pages/home.vue'),
            children: [
                { path: 'random', name: 'random', meta: { requiresAuth: true }, title: 'Random', component: require('./pages/random.vue') }
            ]  
        }
    ]
})

// Redirect to login page if not logged In
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // this route requires auth, check if logged in
        // if not, redirect to login page.
        if (!router.app.auth.isUserLoggedIn) {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        } else {
            next()
        }
    } else {
        next() // make sure to always call next()!
    }
})

Now, when invoking this.login, it simply calls vuex to update the logged-in user.

The issue arises after logging in successfully - the URL changes to /home, but the DOM does not update!

The only solution that has worked to update the DOM was by forcing a location.reload(), but I would like to avoid this as it disrupts dynamically loaded scripts in the Head section.

Do you have any suggestions on how to force the view to update the DOM?

NOTE: This problem occurs only during the first login attempt of a user; subsequent logins and redirects work correctly.

Answer №1

This solution may not be perfect, but it will effectively update the component in every scenario where the route remains the same.

To implement this, simply replace the existing <router-view/> or

<router-view></router-view>
with:

<router-view :key="$route.path"></router-view>

Answer №2

Vue maximizes component reusability by recycling them whenever feasible. It is advisable to employ the beforeRouteUpdate lifecycle hook to handle situations where a route transition involves switching to another route that utilizes the same component.

Answer №3

Dealing with the issue of "URL changing to /home but the DOM not updating" is a challenge I am facing as well.
In my own project, the presence of the "transition" tag seems to be causing this issue.
I hope this insight proves to be beneficial!

Answer №4

If you want the redirectToAfterLogin function to be recalculated each time, consider moving it into the methods object. This way, the computed property will only change if the v-model it depends on changes. To stay true to the function name, I suggest placing the router push inside the function.

In your login.vue file:

mounted: function(){
   if (this.auth.isUserLoggedIn){
            // Let's just redirect to the main page
            // this.$router.push(this.redirectToAfterLogins)
            this.redirectToAfterLogins()
   }else{
            Vue.nextTick(() => {
                this.loadGooglePlatform()
            })
   }
},
// computed: {
methods: {
    this.login(userData).then( 
       // () => this.$router.push(this.redirectToAfterLogin), // Login success
       () => this.redirectToAfterLogin(), // Login success
       () => {} // Login failed
    ),
    redirectToAfterLogin: function() {
            
        if (this.$route.query.redirect){
            // return this.$route.query.redirect
            this.$router.push(this.$route.query.redirect)
        }else{
            // return '/'
            this.$router.push('/')
        }
    }
}

"However, the difference is that computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed. This means as long as message has not changed, multiple access to the reversedMessage computed property will immediately return the previously computed result without having to run the function again."

methods vs computed and filters :

  • Access vue instance/data inside filter method

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 a Vuejs button function that will add together two given numbers

Help needed with VueJs code to display the sum of two numbers. Seeking assistance in developing a feature that calculates the sum only when the user clicks a button. Any guidance would be greatly appreciated! <!DOCTYPE html> <html lang="en"> ...

MenuIcon Component is experiencing difficulty being rendered

I am attempting to construct an IconMenu within the AppBar Component. My project is being developed using create-react-app. This is how my code appears: index.js import React from 'react'; import ReactDOM from 'react-dom'; import &a ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

React Native: Once a user has successfully logged in, I would like the app to automatically direct them to the "Home" screen

After a user signs in, I would like my app to navigate home. However, it seems this is not working because the roots have not been updated. You can view the App code here to get a better understanding of what I am trying to communicate. What is the most e ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

Dynamic font sizing in CSS allows text on a webpage to

I am working on creating a dynamic screen using AngularJS. Within this screen, there are objects with a specific size: .item { margin: auto; margin-bottom: 10px; width: 11vw; height: 11vw; text-overflow: ellipsis; overflow: hidden; } These i ...

Tips on utilizing browser scroll for horizontal overflow of internal div?

I'm working on creating a dynamic page with a tree-like structure that easily exceeds the width of the browser window. My goal is to enable horizontal scrolling for the entire page using the browser's scrollbar, without needing a separate scrollb ...

Deciphering the Essence of Promise Sequences

In my NodeJS project, I am utilizing Promises and aiming to gain a better understanding of Promise.chains. Within the project, there is one exposed function: This main library function returns a promise and it is intended for users to call. After calling ...

I am looking for a way to retrieve the ids of all div elements that have the same x coordinate using document.elementFromPoint in JavaScript. Can someone help me with

Currently, I am facing an issue where I have two divs positioned at the same x coordinate. I am attempting to retrieve the IDs of both divs using document.elementFromPoint(). However, I am only able to receive the ID of one div. var elem = document.elem ...

simultaneous ajax requests - encountering issues in getting a response from the initial one

I'm in the process of developing a small "ping" tool to verify the connectivity of our two servers. Here is the snippet of JavaScript code I am using: var t1, t2, t3, t4; function jsContactServers() { ajaxServerStatusWWW(); ajaxServerStatus ...

Mongoose and ES6 promises are not delivering the expected results

I'm currently working on a piece of code that involves creating an array of promises to save specific numbers. The issue I'm facing is that when the output is printed, it displays the same record 10 times. Below is the code snippet: 'use s ...

Personalizing File Selection

What is the process for customizing file uploads? <%= f.file_field :image, class: 'inputfile' %> <label for="image">Choose an image</label> I am looking to replace "choose an image" with "choose a file" ...

When the page is reloaded, Vuex state does not provide any feedback

The Vuex Authentication in my application is responsible for storing the state of signed-in user data. Everything works correctly during the sign-in process, but I encounter an issue when I reload the page. After reloading, the mutation payload returns n ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

Error in NodeJS: 'Cannot alter headers once they have been sent.'

My project involves developing an app with Express that fetches tweets from Twitter. Each API call retrieves 200 tweets (or fewer if there are less than 200) and in total, I need to retrieve 1800 tweets. To achieve this, I use a time interval to make multi ...

Navigating through intricate JavaScript objects

I am working with an object that looks like this: var obj = { "00a9": ["\u00A9", ["copyright"]], "00ae": ["\u00AE", ["registered"]], "203c": ["\u203C" ...

Using JQuery to make an AJAX request with URL Rest path parameters

Currently, I have a REST service located at /users/{userId}/orders/{orderId} and I am looking to make a call to it using JQuery. Instead of simply concatenating the IDs like this: $.get( 'users/' + 1234 + '/orders/' + 9876, fu ...

How can we verify the validity of URLs based on their length, presence of capital letters, and specific whole words?

I'm currently working on a piece of code that verifies the URL provided by users during sign-up for my application. I want to implement the following restrictions: URL must be at least 3 characters long No capital letters allowed Avoid certain words ...

Clicking on the Angular Material Table will reveal the items for display

Only when I click on the table do items display. Upon initially loading the page, the table is empty for reasons unknown to me. I retrieve data from Rest-API Cloud Blobstorage and populate the empty Array with it. Check out the code snippet below: impor ...