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

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

What is the best way to access and manipulate data stored in a Firestore map using React?

In my Firestore database, I have a field with map-like data: coordinates:{_01:"copper",_02:"gold",_03:"iron"} When viewing this database in the Firestore admin panel, it appears like this: pic However, when attempting to list items using the following c ...

When the React application loads, loadingbar.js will be mounted initially. However, as the props or states are updated, the object

I recently made the switch from using progressbar.js to loadingBar.js in my React application for widget progress. Everything was working smoothly with progressbar.js, but once I switched to loadingBar.js, I encountered a strange issue. After the page load ...

Sending Information within Controllers with AngularJS

I have a unique scenario in my application where I need to pass input from one view to another. I have set up a service as shown below: .service('greeting', function Greeting() { var greeting = this; greeting.message = 'Default&ap ...

Encountering difficulties in retrieving the JSON data from the web service

My external web service contains JSON data which has been validated using the JSON Validator website. However, I am facing an issue where the success function in the code below is not running at all. The web service necessitates that the email and password ...

Enabling communication between App.js and a separate class in React

How can I integrate React Scheduler with JSON data in my app and pass shifts and functions from App.js to DataSheet.js for updating the data? Is there a more efficient way to enable database updates directly from DataSheet? App.js: import React from &apos ...

Unable to apply ready function in jquery .load

When the document is ready, the following code is executed: jQuery(document).ready(function(){ jQuery('#button').click(function() { jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt"); ...

Next.js components do not alter the attributes of the div element

I am encountering a problem with nextjs/reactjs. I have two tsx files: index.tsx and customAlert.tsx. The issue that I am facing is that the alert does not change color even though the CSS classes are being added to the alert HTML element. Tailwind is my c ...

Having trouble with the pagination feature while filtering the list on the vue-paginate node

In my current project, I have integrated pagination using the vue-paginate node. Additionally, I have also implemented filtering functionality using vue-pagination, which is working seamlessly. Everything works as expected when I enter a search term that d ...

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

What is the best way to incorporate both images and text in PHP code?

I'm currently working on creating a large image call-to-action (CTA) for my new WordPress website. I've set up a new field group with the type "group" in ACF, and added some functions in PHPStorm. However, none of my images, text, or links are ap ...

Creating a search filter in Vue.js becomes a breeze with the power of the map function

I attempted a search in Vue, but unfortunately it was not successful. I tried creating a computed function to filter products based on a search term, but for some reason it is not working correctly. Here are my products: async getProducts() { this.$ ...

What could be causing the code to produce 4 elements instead of the expected 2?

I'm trying to understand why the code above is creating four new paragraphs instead of just two. Can someone please explain what exactly happens in the $("p").before($("p").clone()); part? <!DOCTYPE html> <html> <head> <script ...

Having trouble passing parameters to Next JS when using the Courtain.js library

Greetings everyone, I am in the process of developing a website and I have encountered an issue with inserting a distorted image with animation on the homepage. After using a library called Courtain.js, a developer managed to make it work and provided me ...

How do you typically approach testing Cloud Code on Parse?

While working on developing a substantial amount of business logic in webhooks like beforeSave/afterSave/etc. using Parse.com, I have encountered some challenges as a JavaScript/Parse beginner. The process seems somewhat tedious and I'm questioning if ...

Is it possible for users to circumvent limitations on specific routes or pages in a Vue.js application by exploiting the fact that all the code is processed on the client

When developing a single page application utilizing technologies like Firebase, do API keys remain hidden from users since all code is executed on the client side? Additionally, given that users are limited to specific routes or pages based on conditions ...

Unable to display the value of my array in JSON encoded PHP due to it being undefined

In my cart.php file, I have encoded an array to JSON and returned it to an AJAX function: $data = array(); $data['total'] = '10000'; $data['quantity'] = '10'; echo json_encode($data); In my index.php f ...

The code for populating the lookup does not perform as expected on the initial attempt

I've encountered an issue with my JavaScript code on a form where it auto populates 2 lookup fields with the current user when the record is being created. Most of the time, this function works as intended. However, I've noticed that during the f ...

Here's a new version: "Strategies for deactivating a text field in a desktop application that

I am currently using WiniumDriver to automate a desktop application. My goal is to disable a text field once a value has been entered into it. // Launch the desktop application WiniumDriver driver = null; DesktopOptions option = new DesktopOptions(); o ...

Angular is using double quotes (%22) to maintain the integrity of the data retrieved from JSON responses

After running a PHP script, the following response is returned: {"result": "0", "token":"atoken" } To execute the script with Angular, the following code is used: $http.post( API["R001"], $scope.user, {}).then($scope.postSuccess, null); Upon successful ...