ChatGPT解决这个技术问题 Extra ChatGPT

Do we have router.reload in vue-router?

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.


S
Soviut

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.


Yes, it's doing a page refresh and not a component reload.
Note that $router.go() accepts one parameter, so you should use it as $router.go(0), meaning navigate zero pages back in history
@Dan FWIW, I'd say the fact that both github.com/vuejs/vue-router/blob/dev/src/index.js#L175 & it's implementations (e.g. 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 developer.mozilla.org/en-US/docs/Web/API/History/go#Parameters). I've filed a bug report about it @ github.com/vuejs/vue-router/issues/3065, though.
window.location.reload(forceReload) seems to be deprecated, but window.location.reload() is ok.
I
Ian Pinto

The simplest solution is to add a :key attribute to :

<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.


vuejs.org/v2/api/#key in the official docs indirectly explains the mechanism of the key special attribute in vue.
This will not work, because in the scenario the OP is discussing the full path will not change.
Worked great for me. Upvoted this answer.
finally I know what the key is used for.. Thank you this solved my problem
when router-view is used in combination with keep-alive then the key must be placed on component itself, as stated in this answer stackoverflow.com/questions/66215625/…
t
t_dom93
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"

This won't refresh any data on Safari
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 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.
D
Dharman

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


Y
Yun

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')

F
For the Name

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.


A
Abid
`<router-link :to='`/products`' @click.native="$router.go()" class="sub-link"></router-link>`

I have tried this for reloading current page.


L
LiHao

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"/>

T
Tim Titus

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


E
Eduardo Cuomo
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:

And the # must have some value after it. The second route hash is a space, not empty string. setTimeout, not $nextTick to keep the url clean.


Б
Богдан Чернявський

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>

K
Kai - Kazuya Ito

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>

R
RRR

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


K
Kai - Kazuya Ito
vueObject.$forceUpdate();

Why don't you use forceUpdate method?


N
Nimantha
window.location.reload();

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


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.