vue-router: Force navigation when clicking on a router-link even if the route doesn't change

Hey there. This is more of a question than a bug, but could turn into a feature request, if there is no way to currently handle this.

tl;dr; - Is there some way for me to use a global hook and run some code regardless if the current page is the page that will be navigated too?

I’m trying to call some methods (Vuex commits actually) in the vue-router beforeEach or afterEach hooks. These methods do things like closing the navigation, which need to be ran when clicking every link in the application. Everything works like a charm, until the user clicks a link to the page they are currently on. It seems (as it should) that the page doesn’t actually change, but also that none of the hooks are called.

Thanks!

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Reactions: 16
  • Comments: 32 (3 by maintainers)

Commits related to this issue

Most upvoted comments

IMO, Vue Router should respect the “default” behavior of any “normal” link.

On a simple HTML page, when clicking on the link of the page we already are on, the page reload. And I think Vue Router should not alter this default behavior, because it’s what most user using the web is expecting.

I just made a similar comment in #2963, but it seems relevant here as well (and also this issue is still open 😉 ). I believe there are three different use-cases hidden behind a duplicate navigation:

  1. reload (as reported in the current issue)
  2. reject (as is the current behaviour as of #2862)
  3. ignore(as in #2963 and #2872 and was the behaviour before #2862)

My suggestion is to make this configurable like so:

const router = new Router({
    routes: [],
    duplicateNavigationPolicy: 'reload' // other options: 'ignore' and 'reject'
})

I’d be happy to try and open a PR over the weekend, if this is something that would be considered.

Edit: Changed the suggested configuration value for the current behaviour to reject

This really should be addressed. Vue Router is currently incompatible with how the web works. Gmail, YouTube, Facebook, GitHub – they all perform some action when a link that is already active is clicked; some of them even completely reload the view, just like non-SPA sites do. Ignoring active links by default in Vue Router could be a premature optimization, but the lack of a configuration option is a significant flaw.

Edit: I’ve implemented my own router library to circumvent this: https://github.com/adamsol/vue-pocket-router.

@posva was this fixed in v4 and not documented?

For vue-router 4 there seems to be an undocumented API: <router-link :to="{path:'/mypath', force: true}"> (source).

Would be helpful to have a recommendation here in this issue for how to solve this use case generally prior to 4.x.

In my application, like others that have been described, I have a navigation pane (v-navigation-drawer with v-list) with links (each v-list-item has a ‘to’ property) and need each link to always fetch the latest data from the server, including re-clicking the same link we are on now.

The current loader is triggered by a watcher on $route() as well as when created() is fired. A v-on:click method fires after navigation, so it isn’t possible to tell whether navigation happened or not, and I don’t want to redo the loading from the server if it did.

Didn’t think about that! I will give it a shot. Thanks for the suggestion! Keep up the great work! Maybe one day I’ll have the pleasure of being a collaborator on Vue; really enjoying working with it.

I have a simple idea to solve this feature and maybe more flexible, I wrote my idea at this RFC: https://github.com/vuejs/rfcs/discussions/483

This RFC provides a router lifecycle that allows us to do something when the user navigates to the same route as the current page, through this lifecycle we can have more flexibility to update specific data without reloading all pages.

If this feature can help to the situation you are facing or if you have more suggestions for this RFC, welcome to feedback.

works for me if router-view has :key with unique value "vue-router": "4.0.12"

This is extremely relevant. Currently, I’m basically forced to put a “Back to top” link in the page’s footer and always end up with at least one dead link to the same page. It would be really useful if we could just listen for changes to the same route somehow.

@posva: You added the “has workaround” tag but what is the recommended workaround for this?

I have a partial workaround I’ve used for situations involving form submission based on response details but I would prefer a one size fits all straightforward approach as mentioned in #2430 or above (details listed below).

I think the best approach would be to make <router-link> link agnostic, i.e. if the user clicks on a link the router should not care about the link destination and instead perform all the standard operations to navigate to that route such as navigation guards, mounting, beforeRouteEnter, beforeRouteUpdate, etc. just as is the case if the user clicks F5 to reload the whole page. It should be up to the developer to disable or not provide a link if the user should not click it.

==============================================================================

Partial Workaround:

image

==============================================================================

Potential Solution described in #2430:

image

==============================================================================

Potential Solution described in #974 (above):

image

I also think this behavior is really annoying. I often click a link again, to reload the news, restart the form input or just start from scratch. Vue should mimic the default browser behavior or at least it should be configurable. I can’t imagine a reason why it is implemented the way it is. The user clicks a link, so the user wants obviously something to happen.

At the moment it is very difficult to manage. Many solutions are taking about @click.native but this doesn’t work as the router operation is executed first and then the click handler. I ended up with some pages being loaded twice at each click

What I came up with is the following: 1. <router-view :key="this.$store.state.ui.navigationClicked"></router-view> 2. And a custom Component with a mousedown event firing before the router executes:

     <router-link
                @mousedown.native="mousedown"
                ...

      mousedown() {
                if (this.$route.path === this.path) {
                    this.$store.commit("navigationClicked");
                }
            },  

I really think this should be fixed inside Vue.js.

I didn’t do anything here yet, as I’d like to get feedback from a maintainer first on whether a PR like this would even be considered.

It makes sense not to call the hooks because there’s no navigation since it’s the same route. @DevanB What code do you need to run on that case?

Edit: The easiest workaround to trigger a new navigation is to include a fake query or hash so the route is indeed different and the navigation isn’t aborted, e.g. $router.push({ query: { ...$route.query, t: Date.now() }})

Woohoo! IT seems this feature is finally added yes? We can probably close this issue then!

so is update going to be done or not?

The are legitimate use cases in loading the exact same URL but with different underlying params.

Still no native solution for this? My customers are reporting that the expected behavior (refreshing the page) is not working. I would like to avoid any js hack or dirty solutions.

Just an update for any people that may want to solve this in a similar manner. I solved it by creating, importing and using this component, instead of router-link:

RouterLink.vue

<script>
  import { mapActions } from 'vuex'
  export default {
    methods: {
      ...mapActions([ 'closeIsiAndNavigation' ])
    },
    name: 'RouterLink',
    props: {
      to: {
        type: String,
        required: true
      },
      tag: {
        type: String,
        required: false,
        default: 'a'
      }
    },
    render (h) {
      return (
        <div onClick={ this.closeIsiAndNavigation }>
          <router-link to={ this.to } tag={ this.tag }>{ this.$slots.default }</router-link>
        </div>
      )
    }
  }
</script>

Again, thanks for the suggestion @posva. It’s working beautifully.