目录

定义路由(Defining Routes)

路由器将当前URL与负责显示模板,加载数据和设置应用程序状态的路由进行匹配。 router map()方法用于定义传递函数的URL映射,该函数将参数作为对象来创建路由。 {{ link-to }}帮助程序导航路由器。

要定义路径,请在项目文件夹中使用以下命令 -

ember generate route route-name

它创建路径文件app/routes/name_of_the_route.js,app/templates/name_of_the_route.hbs的路径模板,以及tests/unit/routes/route_name_of_the_test.js单元测试文件。

您可以使用路由器的map()方法定义URL映射。 可以使用此值调用此方法以创建用于定义路径的对象。

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

上面的代码显示了如何使用路由器映射链接不同的页面。 它将linkpage名称和路径作为参数。

下表显示了不同类型的路线 -

S.No. 路线和描述
1 Nested Routes

它通过在另一个模板中定义模板来指定嵌套路由。

2 Dynamic Segments

它以:在route()方法中开头,后跟一个标识符。

3 Wildcard/Globbing Routes

通配符路由用于匹配多个URL段。

例子 (Example)

以下示例显示如何定义显示数据的路径。 打开在app/templates/下创建的.hbs文件。 在这里,我们使用以下代码创建了routedemo.hbs文件 -

<h2>My Books</h2>
<ul>
   <li>Java</li>
   <li>jQuery</li>
   <li>JavaScript</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('routedemo');
});
export default Router;

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

//link-to is a handlebar helper used for creating links
{{#link-to 'routedemo'}}BookDetails{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages will 
appear inside this section

输出 (Output)

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

Ember.js定义路线

当您单击输出的链接时,将生成如以下屏幕截图中的结果 -

Ember.js定义路线
↑回到顶部↑
WIKI教程 @2018