Isaac Hatilima
Isaac Hatilima

Reputation: 213

Redirect with page reload Vue JS Router

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
    });

Upvotes: 5

Views: 19459

Answers (2)

Seangle
Seangle

Reputation: 638

You can use this.$router.go(0) to reload the page. You need the 0 if you use Typescript as mentioned by @Second2None. In combination with this.$router.push({ path: '/some/path' }) you can achieve it without directly changing the browser's window property.

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

Notice how I used .then after $router.push(). Because the push() method is asynchronous, the reload would happen before the route change without then().

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


Example with Composition API and async/await syntax:

<script setup>

import { useRouter } from 'vue-router'
const router = useRouter()

const redirectReload = async () => {
  await router.push({ path: '/expedition' })
  router.go(0)
}

</script>

Update

I recommend checking out this thread as there are answers that describe how to reload the page component without reloading the whole website using the :key prop and other useful information.

Upvotes: 12

TrippleN
TrippleN

Reputation: 144

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

Upvotes: 3

Related Questions