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

Wildcard/Globbing Routes

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

通配符路由用于匹配多个路由。 它捕获当用户输入错误的URL并显示URL中的所有路由时有用的所有路由。

语法 (Syntax)

Router.map(function() {
   this.route('catchall', {path: '/*wildcard'});
});

通配符路由以星号(*)符号开头,如上面的语法所示。

例子 (Example)

以下示例指定具有多个URL段的通配符路由。 打开在app/templates/下创建的文件。 在这里,我们使用以下代码创建了文件dynamic-segment.hbsdynamic-segment1.hbs -

dynamic-segment.hbs

<h3>Key One</h3>
Name: {{model.name}}
{{outlet}}

dynamic-segment1.hbs

<h3>Key Two</h3>
Name: {{model.name}}
{{outlet}}

打开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() {
   //definig the routes
   this.route('dynamic-segment', { path: '/dynamic-segment/:myId', 
      resetNamespace: true }, function() {
      this.route('dynamic-segment1', { path: '/dynamic-segment1/:myId1', 
         resetNamespace: true }, function() {
         this.route('item', { path: '/item/:itemId' });
      });
   });
});
export default Router;

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

<h2 id = "title">Welcome to Ember</h2>
{{#link-to 'dynamic-segment1' '101' '102'}}Deep Link{{/link-to}}
<br>
{{outlet}}

routes文件夹下,使用以下代码定义dynamic-segment.jsdynamic-segment1.js的模型 -

dynamic-segment.hbs

import Ember from 'ember';
export default Ember.Route.extend ({
   //model() method is called with the params from the URL
   model(params) {
      return { id: params.myId, name: `Id ${params.myId}` };
   }
});

dynamic-segment1.hbs

import Ember from 'ember';
export default Ember.Route.extend ({
   model(params) {
      return { id: params.myId1, name: `Id ${params.myId1}` };
   }
});

输出 (Output)

运行ember服务器,你会得到以下输出 -

Ember.js通配符路由

当您单击输出上的链接时,您将看到URL路由为/dynamic-segment/101/dynamic-segment1/102 -

Ember.js通配符路由