196

I see in this pull request:

  • Add a router.reload()

    Reload with current path and call data hook again

But when I try issuing the following command from a Vue component:

this.$router.reload()

I get this error:

Uncaught TypeError: this.$router.reload is not a function

I searched in the docs, but could not found anything relevant. Does vue/vue-router provider some functionality like this?

The software versions I'm interested in are:

"vue": "^2.1.0",
"vue-router": "^2.0.3",

PS. I know location.reload() is one of the alternatives, but I'm looking for a native Vue option.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • Why would you reload it anyway? The reactivity is supposed to do its job for you. It's also quite similar to [Can you force Vue.js to reload/re-render?](https://stackoverflow.com/q/32106155/8816585). – kissu Dec 03 '22 at 18:18

18 Answers18

266

this.$router.go() does exactly this; if no arguments are specified, the router navigates to current location, refreshing the page.

note: current implementation of router and its history components don't mark the param as optional, but IMVHO it's either a bug or an omission on Evan You's part, since the spec explicitly allows it. I've filed an issue report about it. If you're really concerned with current TS annotations, just use the equivalent this.$router.go(0)

As to 'why is it so': go internally passes its arguments to window.history.go, so its equal to windows.history.go() - which, in turn, reloads the page, as per MDN doc.

note: since this executes a "soft" reload on regular desktop (non-portable) Firefox, a bunch of strange quirks may appear if you use it but in fact you require a true reload; using the window.location.reload(true); (https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) mentioned by OP instead may help - it certainly did solve my problems on FF.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • 11
    Yes, it's doing a page refresh and not a component reload. – EscapeNetscape Oct 24 '18 at 09:48
  • {this.$router.go()}" class="btn btn-lg btn-danger"> – Vsevolod Azovsky Oct 23 '19 at 08:25
  • 27
    Note that `$router.go()` accepts one parameter, so you should use it as `$router.go(0)`, meaning _navigate zero pages back in history_ – Dan Dec 15 '19 at 19:07
  • 1
    @Dan FWIW, I'd say the fact that both https://github.com/vuejs/vue-router/blob/dev/src/index.js#L175 & it's implementations (e.g. https://github.com/vuejs/vue-router/blob/dev/src/history/html5.js#L40) don't mark the param as optional is either a bug or an omission on Evan You's part, since the spec explicitly allows it (see https://developer.mozilla.org/en-US/docs/Web/API/History/go#Parameters). I've filed a bug report about it @ https://github.com/vuejs/vue-router/issues/3065, though. –  Dec 15 '19 at 20:00
  • 1
    `window.location.reload(forceReload)` seems to be deprecated, but `window.location.reload()` is ok. – henon May 26 '20 at 20:13
  • all answers here are wrong, go without param is not allowed, also go(0) is not working, same error. – MushyPeas Jun 03 '21 at 15:20
  • location.reload(); Work for me in typescript. – Snoozer Mar 03 '22 at 15:29
  • it doesn't work with safari – CodeLikeNoonesBusiness Sep 28 '22 at 02:41
  • For people coming here, vue confirmed themselves there is *no* reload. This answer might've worked at the time, but is no longer accurate. – xorinzor Nov 17 '22 at 15:03
  • This worked fine in my Vue3 application using composition API: `import { useRouter } from 'vue-router';`, `const router = useRouter();`, `router.go(0);` – Anna Madsen May 04 '23 at 10:54
79

The simplest solution is to add a :key attribute to <router-view>:

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

This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.

kissu
  • 40,416
  • 14
  • 65
  • 133
Ian Pinto
  • 2,199
  • 1
  • 21
  • 24
  • 1
    https://vuejs.org/v2/api/#key in the official docs indirectly explains the mechanism of the key special attribute in vue. – Ian Pinto Apr 30 '19 at 18:53
  • 3
    This will not work, because in the scenario the OP is discussing the full path will not change. – Nick Coad Mar 04 '20 at 23:23
  • 2
    Worked great for me. Upvoted this answer. – ak22 Dec 10 '20 at 14:48
  • finally I know what the key is used for.. Thank you this solved my problem – Alex Dec 13 '21 at 16:10
  • when `router-view` is used in combination with `keep-alive` then the `key` must be placed on `component` itself, as stated in this answer https://stackoverflow.com/questions/66215625/vue-3-keep-alive-cache-routes – Alex Dec 22 '21 at 18:12
52
this.$router.go(this.$router.currentRoute)

Vue-Router Docs:

I checked vue-router repo on GitHub and it seems that there isn't reload() method any more. But in the same file, there is: currentRoute object.

Source: vue-router/src/index.js
Docs: docs

get currentRoute (): ?Route {
    return this.history && this.history.current
  }

Now you can use this.$router.go(this.$router.currentRoute) for reload current route.

Simple example.

Version for this answer:

"vue": "^2.1.0",
"vue-router": "^2.1.1"
t_dom93
  • 10,226
  • 1
  • 52
  • 38
  • 2
    This won't refresh any data on `Safari` – jilen May 18 '17 at 09:48
  • 9
    Is there a way to just reload the component, without refreshing the page ? The route should be same, let's say '/users'. But when i click on refresh button, it has to refresh the entire page, without reloading the page. – Rajeshwar Oct 26 '18 at 14:32
  • @Rajeshwar give a `:key` value to the component and change the value when you want to reload that component. This will trigger beforeDestroy() and start the component lifecycle from the beginning. – bariscc Apr 07 '22 at 02:54
13

Use router.go(0) if you use Typescript, and it's asking arguments for the go method.

Dharman
  • 30,962
  • 25
  • 85
  • 135
StvnSpnz
  • 293
  • 4
  • 11
9

router.js

routes: [
{
  path: '/',
  component: test,
  meta: {
    reload: true,
  },
}]

main.js

import router from './router';

new Vue({
  render: h => h(App),
  router,
  watch:{
    '$route' (to) {
       if(to.currentRoute.meta.reload==true){window.location.reload()}
  }
}).$mount('#app')
Yun
  • 3,056
  • 6
  • 9
  • 28
Alfarouq
  • 173
  • 1
  • 6
  • 1
    Ah, but this actually reloads the browser window. I think most people here are interested in maintaining the SPA, just re-rendering the current route (view). – Kalnode Aug 01 '22 at 14:10
  • to.currentRoute is undefined in my application, but to.meta did the trick! Great – ESP32 Jan 16 '23 at 20:55
6

Resolve the route to a URL and navigate the window with Javascript.

        let r = this.$router.resolve({
        name: this.$route.name, // put your route information in
        params: this.$route.params, // put your route information in
        query: this.$route.query // put your route information in
      });
      window.location.assign(r.href)

This method replaces the URL and causes the page to do a full request (refresh) rather than relying on Vue.router. $router.go does not work the same for me even though it is theoretically supposed to.

For the Name
  • 2,459
  • 18
  • 17
3
<router-link 
  :to='`/products`'
  @click.native="$router.go()"
  class="sub-link"
>
</router-link>

I have tried this for reloading the current page.

kissu
  • 40,416
  • 14
  • 65
  • 133
Abid
  • 477
  • 1
  • 4
  • 15
3

Here's a solution if you just want to update certain components on a page:

In template

<Component1 :key="forceReload" />
<Component2 :key="forceReload" />

In data

data() {
  return {
    forceReload: 0
  {
}

In methods:

   Methods: {
     reload() {
        this.forceReload += 1
     }
   }

Use a unique key and bind it to a data property for each one you want to update (I typically only need this for a single component, two at the most. If you need more, I suggest just refreshing the full page using the other answers.

I learned this from Michael Thiessen's post: https://medium.com/hackernoon/the-correct-way-to-force-vue-to-re-render-a-component-bde2caae34ad

Tim Titus
  • 379
  • 3
  • 18
3

A simple example:

this.$router.go(0)

Here is docs: https://router.vuejs.org/guide/essentials/navigation.html#traverse-history

Ilya Degtyarenko
  • 1,359
  • 8
  • 16
2

It's my reload. Because of some browser very weird. location.reload can't reload.

methods:{
   reload: function(){
      this.isRouterAlive = false
      setTimeout(()=>{
         this.isRouterAlive = true
      },0)
   }
}
<router-view v-if="isRouterAlive"/>
kissu
  • 40,416
  • 14
  • 65
  • 133
LiHao
  • 290
  • 3
  • 13
1
function removeHash () { 
    history.pushState("", document.title, window.location.pathname
                                          + window.location.search);
}


App.$router.replace({name:"my-route", hash: '#update'})
App.$router.replace({name:"my-route", hash: ' ', params: {a: 100} })
setTimeout(removeHash, 0)

Notes:

  1. And the # must have some value after it.
  2. The second route hash is a space, not empty string.
  3. setTimeout, not $nextTick to keep the url clean.
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
Justin Alexander
  • 2,004
  • 3
  • 21
  • 25
1

For rerender you can use in parent component

<template>
  <div v-if="renderComponent">content</div>
</template>
<script>
export default {
   data() {
      return {
        renderComponent: true,
      };
    },
    methods: {
      forceRerender() {
        // Remove my-component from the DOM
        this.renderComponent = false;
        
        this.$nextTick(() => {
          // Add the component back in
          this.renderComponent = true;
        });
      }
    }
}
</script>
kissu
  • 40,416
  • 14
  • 65
  • 133
1

Simple reload/refresh any component do below things

<ProductGrid v-if="renderComponent"/>

<script>
import ProductGrid from "./product-grid";
export default {
  name:'product',
  components: {
    ProductGrid
  },
  data() {
    return {
      renderComponent: true,
    };
  },
  methods: {
    forceRerender: function() {
      // Remove my-component from the DOM
        this.renderComponent = false;
        this.$nextTick(() => {
            // Add the component back in
            this.renderComponent = true;
        });
    }
 },
 watch:{
    '$route.query.cid'(newId, oldId) {
        if(newId>0){
            this.forceRerender();
        }      
     }
  }
}
</script>
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Dhara Bhalala
  • 224
  • 1
  • 5
0

Found a way to go to reload same route from same source on vue router 4:

import {
  useRouter,
  NavigationFailureType,
  isNavigationFailure,
} from "vue-router";

const router = useRouter();
const handleLinkClick = (link) => {
  router.push({ name: link }).then((failure) => {
    if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
      router.go({ name: link });
    }
  });

source

RRR
  • 507
  • 4
  • 17
0

This answer helped me:

 this.$router
          .push({ path: '/home' })
          .then(() => { this.$router.go() })

It first redirects to /home and then reloads the page. Helps with getting updated navbar after login.

parsecer
  • 4,758
  • 13
  • 71
  • 140
-2

if you mean to reload the page just do:

window.location.reload()
  • Thank you for your contribution! I would recommend looking at @Enver's answer though, and either editing Enver's answer or addressing the concerns in the comments in your answer. – Chris Happy Jun 12 '23 at 20:14
-4
vueObject.$forceUpdate();

You could use the forceUpdate method.

kissu
  • 40,416
  • 14
  • 65
  • 133
-5
window.location.reload();

You can use it to reload your current page. There is similar usage in Jquery too.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Enver
  • 542
  • 5
  • 7
  • 2
    Re-loading the window is the opposite of what one wants to achieve with a PWA. So although the solution technically solves the problem, it is not a useful solution for the problem at hand. – Fred Dec 01 '21 at 12:02
  • 1
    @Fred you probably meant SPA here (rather than PWA). And yep, it's indeed a quite bad practice for such purpose because it's nukes the whole Vue app. – kissu Dec 03 '22 at 18:22
  • The thing is that we're not using jQuery but Vue here, quite important detail. – kissu Dec 03 '22 at 18:22