VueJS:当直接在浏览器中输入URL中的路由时,如何确定“来自”路由?

时间:2019-06-24 19:13:57

标签: javascript vue.js vuejs2 routes vue-router

我有一个Vue应用程序和一些路由(下面将它们称为“ 首页”,“ first_route ”和“ second_route ”) )。在为“ first_route ”路由加载组件之前,我想检查用户的来源。

有两种选择:

  • 应用程序中有一个菜单,当用户单击菜单时,他将尝试访问相应的单击路线(将其想象为一个简单的菜单,其中包含“ Dashboard ”,“ 关于我们”,“ 联系”页面,就我而言,将是“ 第一条路线页面”,“ 第二条路线页面< / em>”,并且在此菜单中还将显示路由“ /”,这是我的应用程序的“ HomePage ”);
  • 当用户在某条路线上时,他可以刷新浏览器,这将再次加载其当前路线。,当他在其他网站(例如Google)上时,可以尝试直接打开像“ www.mypage.com/first_route”这样的路线

通常,这个想法是:

  • 如果用户来自当前应用程序(内部-如果他单击它)
  • 如果用户来自某个外部网站或刷新页面

我在下面发布我的代码,但在下面的块中形成如果条件时遇到问题:

    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路由可识别的值为“ /”。如果我们位于“主页”(路由为“ /”,并且用户单击菜单上并选择“ / first_route ”页面),那么我们将具有相同的条件。

在两种情况下,fromto路由是相同的。这是矛盾的事情:在第一种情况下,我们来自外部站点,在第二种情况下,我们来自“ /”路由(主页),但是在两种情况下,相同的条件(from.path == "/" && to.path == "/first_route")为真,所以我无法确定(从上方)主要两种情况中的哪一种受到了打击。

1 个答案:

答案 0 :(得分:0)

您可以尝试在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')
    }