Ember路由如何配置父级路由返回404、对应子路由可正常访问?
要实现仅/foo/bar/cat可正常访问、/foo和/foo/bar跳转404的需求,有两种常用实现方案:
方案一:新增父路由文件配置拦截逻辑
分别创建app/routes/foo.js和app/routes/foo/bar.js两个路由文件,通过beforeModel钩子判断当前访问的是否为父路由本身,是则跳转404,不会影响子路由的正常访问:
app/routes/foo.js代码:
import Route from '@ember/routing/route'; export default class FooRoute extends Route { beforeModel(transition) { // 仅直接访问foo路由本身时拦截,子路由访问不触发 if (transition.to.name === 'foo') { this.replaceWith('notfound'); } } }
app/routes/foo/bar.js代码:
import Route from '@ember/routing/route'; export default class FooBarRoute extends Route { beforeModel(transition) { // 仅直接访问foo.bar路由本身时拦截,子路由访问不触发 if (transition.to.name === 'foo.bar') { this.replaceWith('notfound'); } } }
方案二:直接修改router.js配置拦截
无需新增路由文件,在原路由定义中显式声明父路由下的index路由并配置重定向即可,Ember访问父路由路径时会默认命中该index子路由:
修改后的router.js完整代码:
import EmberRouter from '@ember/routing/router'; const Router = EmberRouter.extend({}); Router.map(function () { this.route('index', { path: '/' }); this.route('foo', function() { // 访问/foo时命中该index路由,直接跳转404 this.route('index', { path: '/' }, { redirect() { this.replaceWith('notfound'); } }); this.route('bar', function() { // 访问/foo/bar时命中该index路由,直接跳转404 this.route('index', { path: '/' }, { redirect() { this.replaceWith('notfound'); } }); this.route('cat'); }); }); this.route('notfound', { path: '/*path' }); }); export default Router;
两种方案效果完全一致,你可以根据自己的项目习惯选择即可。
内容的提问来源于stack exchange,提问作者Cameron
相关产品推荐
相关产品推荐

