我正在尝试创建一个SPA,显示奥地利各州的经销商。例如,如果用户访问example.com/vienna
,则会显示维也纳的每个经销商。但如果用户访问example.com/paris
,他仍会被定向到动态路线/巴黎,但当然不会显示任何内容。
所以我的方法是检查用户想要搜索的状态是否在状态列表中可用,因此将其指向可用状态或将其重定向到404页面。
如果状态可用,它会起作用,但如果我尝试进入非现状状态,我会陷入next('/404')
的循环
export default new Router({
routes: [{
path: '/',
name: 'Home',
component: Home
},{
path: '/:region',
component: RegionQuery,
beforeEnter: (to, from, next) => {
let isRegion = false;
let allRegions = storeConfig.state.states;
let toRegion = to.params.region;
for(var i in allRegions){
if(allRegions[i].route === toRegion){
isRegion = true;
}
}
if (isRegion) {
next();
} else {
next('/404');
}
}
},
{
path: '/404',
name: '404',
component: NotFound
},
{
path: '*',
redirect: '/404'
},
],
})
我做错了什么或是否有更好的解决方法?
答案 0 :(得分:1)
/404
与/:region
您需要更改路径顺序
export default new Router({
routes: [{
path: '/',
name: 'Home',
component: Home
},
{
path: '/404',
name: '404',
component: NotFound
},{
path: '/:region',
component: RegionQuery,
beforeEnter: (to, from, next) => {
let isRegion = false;
let allRegions = storeConfig.state.states;
let toRegion = to.params.region;
for(var i in allRegions){
if(allRegions[i].route === toRegion){
isRegion = true;
}
}
if (isRegion) {
next();
} else {
next('/404');
}
}
},
{
path: '*',
redirect: '/404'
},
]