Ember.js中仅渲染子模板:父/子路由下如何不加载父模板?
解决Ember.js父/子路由不渲染父模板的问题
有两种可行方案可以实现完全阻止父模板加载:
方法一:重写子路由的renderTemplate钩子
在parent/child对应的路由类中,重写renderTemplate方法,直接指定渲染子模板,跳过父模板的默认渲染流程。示例代码:
// app/routes/parent/child.js import Route from '@ember/routing/route'; export default class ParentChildRoute extends Route { renderTemplate() { // 仅渲染child模板,不加载父模板 this.render('parent/child'); } }
嵌套路由默认逻辑是先渲染父模板,再将子模板插入父模板的{{outlet}}中。重写该方法后,会直接渲染指定的子模板,完全跳过父模板的渲染步骤。
方法二:将子路由设为顶级路由(保留URL结构)
如果不需要父路由的关联逻辑,仅想保留parent/child的URL路径,可以把child定义为顶级路由,通过path参数指定URL格式:
// app/router.js import Router from '@ember/routing/router'; import config from 'your-app/config/environment'; export default class extends Router { location = config.locationType; rootURL = config.rootURL; } Router.map(function() { // 若有其他需要嵌套渲染的子路由,保留parent路由定义 this.route('parent', function() { // 其他子路由 }); // 将child设为顶级路由,URL保持/parent/child this.route('parent-child', { path: '/parent/child' }); });
这种方式下,parent-child路由完全独立,不会触发父模板的渲染,同时满足URL路径需求。
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

