考虑到id
s 是数字,您可以使用:
{
path: '/:id(\\d+)',
name: 'AgentSite',
component: AgentSite
},
仅匹配如果id
仅由数字组成。
Update:有几个人提到了当代理 ID 是数字时有效的解决方案。这是一个好主意,只不过我们已经构建了代理“slugs”来代替。
如果名称可能与现有路线冲突,最后声明代理路由.
来自匹配优先级 docs https://router.vuejs.org/en/essentials/dynamic-matching.html#matching-priority(强调我的):
匹配优先级
有时同一个 URL 可能会被多个路由匹配。在这样一个
case 匹配优先级由路由顺序决定
定义:路由定义越早,优先级越高
得到.
换句话说,声明如下:
routes: [
{
path: '/',
component: HomePage
},
{
path: '/quotes',
component: Quotes
},
{
path: '/clients',
component: Clients
},
{
path: '/:id',
component: AgentSite,
props: true
}
]
See CodeSandbox 演示在这里 https://codesandbox.io/s/kokoqxvl87?module=%2Frouter%2Findex.js.
处理 404 页面
然后我会在“的上方或下方声明404页面路由吗?”AgentSite
“在你的例子中?{ path: "*", component: PageNotFound }
The AgentSite
路线会匹配之前未匹配的任何 URL,所以你必须处理内部的 404AgentSite
成分。
首先声明404路由after the AgentSite
:
routes: [
// ... (other routes)
{
path: "/:id",
component: AgentSite,
props: true
},
{
path: ":path",
name: "404",
component: p404,
props: true
}
]
然后,里面AgentSite
,获取代理:id
,检查它是否是已知代理,如果不是,则重定向到404
route by name(否则会再次匹配代理)。
export default {
props: ["id"],
data() {
return {
availableAgents: ["scully", "bond", "nikita"]
};
},
created() {
let isExistingAgent = this.availableAgents.includes(this.id);
if (!isExistingAgent) {
this.$router.push({
name: "404",
params: { path: this.$route.fullPath.substring(1) }
});
}
}
};
The CodeSandbox 演示在这里 https://codesandbox.io/s/kokoqxvl87?module=%2Frouter%2Findex.js已经包含此处理。