vue.js - 如何使用 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
}
解决方案
以@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: '/' });
}
}
}
]
})
推荐阅读
- c# - 如何根据单击的项目(ASP.NET Core Razor 页面)用表单中的值填充字段?
- javascript - 如何根据我的包装高度检查我创建的项目 y 坐标?
- javascript - 如何使用 Node.js/JavaScript 生成唯一的用户 ID,例如 Zerodha 的用户 ID
- ruby-on-rails - 如何使用 Webpacker 在 JS 项目中使用 TypeScript 包
- deep-learning - ValueError:预期输入 batch_size (1) 与目标 batch_size (100) 匹配
- angular - 如何有条件地为 mat-tab Angular 设置标签?
- c++ - C ++:为什么将函数标记为内联会使“未引用的本地函数已被删除”警告静音?
- javascript - Google Calendar API - 请求的身份验证范围不足
- android - 通过通用链接从 android webview 深度链接到应用程序
- git - gitignore 不工作 .env 文件正在更新