4

I have an app with a Login.vue and Home.vue files. Because I converted an admin HTML website to a vue 3 app, my javascript only works with page reload. When creating the app I selected add router for SPA maybe I shouldn't have. Up to this point, the views are working except when I redirect from login to home without reloading. Since it is not reloading, my navbar or any JS-dependent functions won't work. how do I redirect from login to home with page reload? Currently, I have the below code but still not working.

this.$router.push({
      path: "/admin/home",
      reload: true
    });
Isaac Hatilima
  • 151
  • 1
  • 10

2 Answers2

9

You can use this.$router.go() with empty arguments to reload the page. In combination with this.$router.push({ path: '/admin/home' }) you can achieve it without using vanilla JS features.

<template>
  <button @click="redirectReload">Redirect & Reload</button>
</template>
    
<script>
  export default {  
    methods: {
      redirectReload() {
        this.$router
          .push({ path: '/expedition' })
          .then(() => { this.$router.go() })
      }
    }
  }
</script>

Notice how I used .then after $router.push(). Without then the page reloads too quickly, leaving no time for the route to change.

As a bonus, it lets you use all the features of $router.push (for example using arguments like { name: 'home' }.

Magiczne
  • 1,586
  • 2
  • 15
  • 23
Seangle
  • 359
  • 2
  • 10
  • 1
    Thank you for the response did the trick. – Isaac Hatilima Jul 28 '22 at 11:33
  • I spent a couple hours troubleshooting why the template section of my login page wasn't rendering when I redirected to it using Continue to the login page. This solved my issue. I don't understand why but it works – Todd Hammer May 23 '23 at 12:02
  • For anyone using 'script setup' I did it like this: import { useRouter } from 'vue-router'; const router = useRouter(); const redirectReload = ()=> { router .push({ path: '/login' }) .then(()=> { router.go() }) } – Todd Hammer May 23 '23 at 12:04
  • @ToddHammer your app probably had some problems with component update order. Better to fix that without using crutches like reloading the whole SPA. You better create a new question with more details and ping me – Seangle May 26 '23 at 03:40
2

Vue Router not reload page when you navigate to new URL.

You can try this code for you issue:

const url = new URL('/admin/home', window.location.origin)
window.location.href = url.toString()

Hope this help

TrippleN
  • 114
  • 5