Vue路由器:this。$ router.push是否导航到新URL?

时间:2018-12-09 09:11:12

标签: vue.js vue-router html5-history

我阅读了vue-router(https://router.vuejs.org/guide/essentials/navigation.html)的文档

  

这是单击时在内部调用的方法,   所以点击等同于调用   router.push(...)

据我所知,单击router-link元素会导航到位于“ to”属性中的URL。但是,根据History API (https://developer.mozilla.org/en-US/docs/Web/API/History_API#Examples),history.pushState(...)仅更改历史记录,而不会导航到新的URL。

那么...我们如何解释这个矛盾?

2 个答案:

答案 0 :(得分:2)

这里没有矛盾。 Vue路由器没有理由无法使用历史记录api更改url并更改该组件,使其在各种路由器视图组件中呈现。

当您在代码中包含router-link时,该组件就是其他组件。 Vue将呈现this component。有趣的部分是这样:

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
}

对于历史记录api,您可以看到in the source,对于this.$router.push(..),我们进行了过渡,并使用this pushState function来推动状态。过渡本身可以在history/base.js中找到。

答案 1 :(得分:1)

我认为您需要准确定义“导航到新URL”的含义;对我来说,这可能意味着要么以新的URL重新加载页面,要么只是在地址栏中更改URL而无需重新加载页面。

history.pushState()确实会更改URL,但不会导致浏览器执行单击链接时的典型重新加载整个页面的操作。这就是“单页应用程序”的工作方式-它们拦截<a>次点击,并使用history.pushState()阻止重新加载页面。

  

history.pushState(...)仅更改历史记录,而不会导航到新URL。

在这里,我认为“并且不导航到新的URL”是错误的-确实如此,只是页面不会重新加载。

相关问题