首页 > 解决方案 > 如何使用 vue-router 重定向非动态 url

问题描述

我们有一个用于保险公司的 vue.js 应用程序,每个代理都有自己的动态生成的网站。目前,如果您访问乱码链接,它将显示空白代理模板。我们需要不包含代理 slug 的 url 来重定向到我们的“NotFound”组件。

如果碰巧有一个简单的修复,下面是我们的 vue-router 代码。否则,例如,如果 agent.name == null,添加计算函数来重定向访问者是否更容易?

谢谢你的帮助!

一个好的 url 示例:https ://my.piaselect.com/georgebeach

错误网址示例:https ://my.piaselect.com/georgebeach2

我们的路由器:

{
  path: "/:id",
  component: AgentSite,
  name: 'AgentSite',
  props: true
},
{
    path: '*',
    name: 'NotFound',
    component: NotFound
}

标签: vue.jsvue-router

解决方案


以@Jacob Goh 所说的话为基础。

如果代理 ID 有效与否,您现在需要一种方法。假设您有一个代理 ID 列表,您可以使用路由保护来阻止指向无效 ID 的路由。

https://router.vuejs.org/en/advanced/navigation-guards.html

我没有对此进行测试,但你应该能够得到大致的想法。

const agentIds = ['Bob', 'Michael']

const router = new VueRouter({
  routes: [
    {
      path: '/foo:id',
      component: Foo,
      beforeEnter: (to, from, next) => {
        if (agentIds.includes(to.params.id)) {
          // The agent is fine - continue
          next();
        } else {
          // doesn't exist - go back to root or any other page
          next({ path: '/' });
        }
      }
    }
  ]
})

推荐阅读