![](/img/trans.png)
[英]Vuejs How to stop route params Type from changing when entered from url or router-link
[英]VueJS: How to determinate the “from” route, when route in URL is directly entered in browser?
我有一個Vue應用程序和一些路由(讓我們將它們稱為“ 主頁 ”,“ first_route ”和“ second_route ”)。 在為“ first_route ”路由加載組件之前,我想檢查用戶來自何處。
有兩種選擇:
一般來說,這個想法是:
我在下面發布我的代碼,我在下面的塊中形成if條件時遇到問題:
export default new Router({
mode: 'history',
routes: [
{
path: "/",
component: HomePage
},
{
path: "/first_route",
component: FirstRoutePage,
beforeEnter (to, from, next) {
if (check where the route comes from)
// do something if the route comes from page refresh
// or if user directly entered "/first_route" from external site
} else {
// do something else if the route comes as a result of
// a user click from another route (internal, from the menu)
}
}
},
{
path: "/second_route",
component: SecondRoutePage
}
]
我試過的是檢查:
beforeEnter (to, from, next) {
if (to.path == from.path)
// do something if the route comes from page refresh
// or if user directly entered "/first_route" from external site
} else {
// do something else if the route comes as a result of
// a user click from another route (internal, from the menu)
}
}
但這僅涵蓋用戶刷新瀏覽器的情況。 用戶直接將完整URL輸入瀏覽器的情況不在此解決方案中。
主要問題是 :當用戶直接將完整的URL輸入瀏覽器時, from.path
的from路由from.path
值為“/”。 如果我們在“HomePage”(哪條路線是“/”,如果用戶點擊菜單並選擇“ / first_route ”頁面),那么我們將具有相同的條件。
在這兩種情況下, from
和to
路徑是相同的。 這是矛盾的事情:在第一種情況下,我們來自外部網站,在第二種情況下,我們來自“/”路線(HomePage)但在兩種情況下都是相同的條件(from.path == "/" && to.path == "/first_route")
是真的,所以我無法確定哪兩個主要場景(來自上面)被擊中。
您可以嘗試在created()方法中執行此操作。
if (this.$route.params.id)
// do something if the route comes from page refresh
// or if user directly entered "/first_route" from external site
} else {
// do something else if the route comes as a result of
// a user click from another route (internal, from the menu)
}
並在你的路由器中設置id。
{
path: '/example/:id/',
name: 'example',
component: () => import(/* webpackChunkName: "about" */ './components/example.vue')
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.