Vue Router:这个。$router.push 导航到一个新的 URL 吗?
Vue Router: does this.$router.push navigate to a new URL?
我阅读了vue-router的文档(https://router.vuejs.org/guide/essentials/navigation.html)
This is the method called internally when you click a ,
so clicking is the equivalent of calling
router.push(...)
据我所知,单击 router-link 元素会导航到放置在 "to" 属性中的 URL。然而,根据历史 API
(https://developer.mozilla.org/en-US/docs/Web/API/History_API#Examples),history.pushState(...) 仅更改历史记录,不会导航到新的 URL。
所以...我们如何解释这个矛盾?
我认为您需要准确定义 "navigate to a new URL" 的意思;对我来说,这可能意味着在新的 URL 重新加载页面,或者只是更改地址栏中的 URL 而无需重新加载页面。
history.pushState()
确实更改了 URL,但它不会像您单击 link 时那样导致浏览器执行整页重新加载。这就是 "single page apps" 的工作方式——他们拦截 <a>
点击并使用 history.pushState()
来防止页面重新加载。
history.pushState(...) only changes the history and does not navigate to a new URL.
这里我认为 "and does not navigate to a new URL" 是错误的 – 它是错误的,除了页面没有重新加载。
这里没有矛盾。 Vue Router 没有理由不能使用历史 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 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。
我阅读了vue-router的文档(https://router.vuejs.org/guide/essentials/navigation.html)
This is the method called internally when you click a , so clicking is the equivalent of calling router.push(...)
据我所知,单击 router-link 元素会导航到放置在 "to" 属性中的 URL。然而,根据历史 API (https://developer.mozilla.org/en-US/docs/Web/API/History_API#Examples),history.pushState(...) 仅更改历史记录,不会导航到新的 URL。
所以...我们如何解释这个矛盾?
我认为您需要准确定义 "navigate to a new URL" 的意思;对我来说,这可能意味着在新的 URL 重新加载页面,或者只是更改地址栏中的 URL 而无需重新加载页面。
history.pushState()
确实更改了 URL,但它不会像您单击 link 时那样导致浏览器执行整页重新加载。这就是 "single page apps" 的工作方式——他们拦截 <a>
点击并使用 history.pushState()
来防止页面重新加载。
history.pushState(...) only changes the history and does not navigate to a new URL.
这里我认为 "and does not navigate to a new URL" 是错误的 – 它是错误的,除了页面没有重新加载。
这里没有矛盾。 Vue Router 没有理由不能使用历史 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 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。