10
votes

We want that if we click on router-link which is the same page, the page will reload.

How can that be done? watch->$route doesn't invoke if the page stays the same

7
I'm not sure if this is what you want to achieve: stackoverflow.com/questions/52847979/… - Jns
@Jns The route stays the same, so this wont work - Himberjack

7 Answers

5
votes

If your need is just "refresh" the component due to a route parameter change, try this:

// define a watcher 
watch: {
    "$route.params.id"(val) {
      // call the method which loads your initial state
      this.find();
    },
},

where "id" comes from /myroute/:id and find() is a regular method.

2
votes

You can use "beforeEnter" Doc.

   { 
     path: '/foo', component: Foo,
     beforeEnter: (to, from, next) => {
       /*
        todo check if to === from
        Warning!: location.reload()  completely destroy all vuejs stored states
        */
        window.location.reload()
        return next()
     }
   }
1
votes

Consider using @click (or @click.native) on a <router-link> to execute your customs code when the user clicks on it.

Now this seems like a bad idea because you will have to use that method on every <router-link> in any component. A solution would be to wrap the <router-link> pseudo component with another component conveniently(!) called routerLink == <router-link>. I already do something similar with the original <transition> component and it works like a charm. this doesn’t solve the problem of having to import that component and use it inside all components needing <router-link>, but it will mean you have a centralized place to add your custom logic for a clicking event and not repeating it again or modifying it in multiple places when you need to.

I don’t have an available Vue.js project right now to test this on, so if the @click(.native) approach doesn’t work because <router-link> is a pseudo component, just apply the event listener to the newly created custom component.

0
votes
0
votes

One of the options is to use key on RouterView:

<RouterView :key="whenThisVarChangeRouterViewWillBeRemounted" />

Just make sure to put key to something sensible if you don't want to reload on every router view change otherwise you could use:

:key="$router.fullPath"

which will guarantee to remount on every change to path.

0
votes

If you can modify route-link to this.$router.push in a component, and if you don't want to reload whole page like window.location.reload(), consider push a not existing route, then push the same route immediately.

this.$router.push({ name: 'not existing' })
this.$router.push({ name: yourRouteName })

side effect: Vue will warn: [vue-router] Route with name 'not existing' does not exist in console.

0
votes

work for me :) set below code in router-view

:key="$route.fullPath"

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