EmberJS - 路由定義



路由器將當前 URL 與負責顯示模板、載入資料和設定應用程式狀態的路由匹配。路由器的 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 對映。可以使用 this 值呼叫此方法來建立一個用於定義路由的物件。

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

以上程式碼展示瞭如何使用路由對映連結不同的頁面。它以 linkpage 名稱和路徑作為引數。

下表顯示了不同型別的路由:

序號 路由及描述
1 巢狀路由

它透過在另一個模板內定義模板來指定巢狀路由。

2 動態片段

它以 route() 方法中的 : 開頭,後跟一個識別符號。

3 萬用字元/全域性路由

萬用字元路由用於匹配多個 URL 片段。

示例

以下示例展示瞭如何定義用於顯示資料的路由。開啟在 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

輸出

執行 ember 伺服器,您將收到以下輸出:

Ember.js Defining Routes

單擊輸出連結時,將生成如下所示的螢幕截圖:

Ember.js Defining Routes
emberjs_router.htm
廣告
© . All rights reserved.