簡體   English   中英

VueJS:如何在瀏覽器中直接輸入URL中的路由時確定“從”路由?

[英]VueJS: How to determinate the “from” route, when route in URL is directly entered in browser?

我有一個Vue應用程序和一些路由(讓我們將它們稱為“ 主頁 ”,“ first_route ”和“ second_route ”)。 在為“ first_route ”路由加載組件之前,我想檢查用戶來自何處。

有兩種選擇:

  • 應用程序中有一個菜單,當用戶點擊菜單時,他將嘗試訪問相應的點擊路線(想象這是一個簡單的菜單,其中包含“ 儀表板 ”,“ 關於我們 ”,“ 聯系 ”頁面等項目,在我的情況下將是“ 第一路線頁 ”,“ 第二路線頁 ”,我將在此菜單中有“/”路線,這是我申請的“ 主頁 ”;
  • 當用戶在某個路線上時,他可以刷新瀏覽器,這將再次加載他當前的路線, 或者當他在另一個站點(例如谷歌)時,他可以嘗試直接打開路線,如“www.mypage.com/” 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 ”頁面),那么我們將具有相同的條件。

在這兩種情況下, fromto路徑是相同的。 這是矛盾的事情:在第一種情況下,我們來自外部網站,在第二種情況下,我們來自“/”路線(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM