[Vuejs]-Vue Router: does this.$router.push navigate to a new URL?

2đź‘Ť

âś…

I think you need to define exactly what you mean by “navigate to a new URL”; to me it can mean either reloading the page at a new URL, or simply changing the URL in the address bar without reloading the page.

history.pushState() does change the URL, but it doesn’t cause the browser to perform a full page reload as is typical when you click a link. This is how “single page apps” work – they intercept <a> clicks and use history.pushState() to prevent the page from reloading.

history.pushState(…) only changes the history and does not navigate to a new URL.

Here I think “and does not navigate to a new URL” is wrong – it does, except the page doesn’t reload.

👤Decade Moon

2đź‘Ť

There is no contradiction here. There is no reason why the Vue Router could not do a change to the url with the history api and change the component as rendered in various router-view components.

When you include a router-link in your code, this is a component like any other. Vue will render this component. The interesting part is this:

const router = this.$router

// And later
const handler = e => {
  if (guardEvent(e)) {
    if (this.replace) {
      router.replace(location)
    } else {
      router.push(location)
    }
  }
}

const on = { click: guardEvent }
if (Array.isArray(this.event)) {
  this.event.forEach(e => { on[e] = handler })
} else {
  on[this.event] = handler
}

For the history api, you can see in the source that for a this.$router.push(..) we transition, and we push the state with this pushState function. The transition itself can be found in history/base.js.

👤Sumurai8

Leave a comment