EmberJS - 重定向



這是一個 URL 重定向或轉發機制,它使一個網頁可用於多個 URL 地址。Ember.js 定義了一個 transitionTo() 方法,該方法使應用程式進入另一個路由,其行為類似於 link-to 幫助器。

要從一個路由重定向到另一個路由,請在路由處理程式中定義 beforeModel 鉤子。

語法

Ember.Route.extend ({
   beforeModel() {
      this.transitionTo('routeToName');
   }
});

示例

下面給出的示例描述瞭如何從一個路由重定向到另一個路由。建立一個新路由並將其命名為 beforemodel,然後使用以下程式碼開啟 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('posts', function() {
      this.route('beforemodel');
   });
});

//It specifies Router variable available to other parts of the app
export default Router;   

使用以下程式碼開啟在 app/routes/ 下建立的檔案 beforemodel.js

import Ember from 'ember';

export default Ember.Route.extend ({
   beforeModel() {
      //open the beforemodel.hbs page to display the data
      this.transitionTo('beforemodel'); 
   }
});

使用以下程式碼開啟在 app/templates/ 下建立的檔案 beforemodel.hbs

<h2>Hello...Welcome to Tutorialspoint!!!</h2>
{{outlet}}

輸出

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

Ember.js Router Redirecting
emberjs_router.htm
廣告
© . All rights reserved.