当前位置: 首页 > 文档资料 > EmberJS 入门教程 >

Nested Routes

优质
小牛编辑
121浏览
2023-12-01

您可以通过将回调传递给当前路由,在另一个模板中定义模板来定义嵌套路由。

语法 (Syntax)

Router.map(function() {
   this.route('link-page', { path: 'pathTolinkpag' }, function() {
      this.route('link-page');
   });
});

要创建嵌套路由,请运行以下命令 -

ember generate route route_name/another_route_name

例子 (Example)

下面的示例演示如何定义嵌套路由以在另一个模板中显示一个模板。 打开在app/templates/nestedroute下创建的.hbs文件。 在这里,我们使用以下代码创建了fruits.hbs文件 -

<h2>Fruits Page</h2>
<ul>
   <li>Orange</li>
   <li>Apple</li>
   <li>Banana</li>
</ul>

打开router.js文件以定义URL映射 -

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config
//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});
//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('nestedroute', function() {
      this.route('fruits');
   });
});
//It specifies Router variable available to other parts of the app
export default Router;

创建application.hbs文件并添加以下代码 -

{{#link-to 'nestedroute.fruits'}}fruits{{/link-to}}
{{outlet}} 

输出 (Output)

运行ember服务器,您将收到以下输出 -

Ember.js嵌套路线

当您单击输出上的链接时,您将看到URL路由为nestedroute/fruits ,它将显示fruits.hbs的结果 -

Ember.js嵌套路线