John Moore
John Moore

Reputation: 7129

Clicking on active router-link

In my Vue 2 app, I have a menu bar whose menu items use router-link. One of these menu items is 'Customers', which takes the user to a customer editor. Now, if the user clicks on this same 'Customers' menu item while they're in the customer editor, nothing happens. I presume this is because of this behaviour mentioned in the docs: "In HTML5 history mode, router-link will intercept the click event so that the browser doesn't try to reload the page."

Now, that's perfectly understandable and for the majority of the time it would be the behaviour I want. But actually here I want the component to be reloaded, to go back to a clean slate. Or perhaps more accurately, for some event to occur which I can handle within the customer editor to set things how I want them to be. I assumed this would be the case, in fact, but when I set up a watch, thus

    watch: {
      '$route' (to, from) {
        console.log("Route changed");
      }
    },

I don't see anything logged to the console. It may be that some event is occurring which I'm not handling and that Vue is simply reusing the component. But how can I stop it from doing so?

Upvotes: 2

Views: 3933

Answers (2)

sliptype
sliptype

Reputation: 2974

According to this issue, you can add a @click.native binding to the current router-link and reinitialize your component data in there.

But a quick and dirty solution would be to append a unique parameter to your route, like a date. Check this fiddle

Upvotes: 6

zero298
zero298

Reputation: 26920

The intended method of accomplishing this seems to be to implement a beforeRouteUpdate function to reset the properties of the route component. See this issue on vue-router's GitHub: Routing the same component, the component is not reload, but be reused? #1490.

This is expected behaviour, Vue re-uses components where possible.

You can use the beforeRouteUpdate hook to react to a route switch that uses the same component.

Upvotes: 1

Related Questions