Silently update url without triggering route in vue-router

Rinux picture Rinux · Jul 14, 2018 · Viewed 18.9k times · Source

I need to update the hash of the url, without actually triggering the vue-router to go to that route. Something in the likes of:

router.replace('my/new/path', {silent:true})

This would update the url to .../#/my/new/path, but the router itself would not route to that path.

Is there an elegant way to achieve this?

Answer

ManUtopiK picture ManUtopiK · Jun 20, 2019

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addHashToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path + '#' + encodeURIComponent(params)
  )
}

So anywhere in your component, call addHashToLocation('/my/new/path') to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Should work with Vue 2.6.10 and Nuxt 2.8.1.  

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.