Aurelia - 路由

路由是每个应用程序的重要组成部分.在本章中,您将学习如何在Aurelia框架中使用路由器.

步骤1  - 创建页面

我们已经创建了一个组件文件夹在前一章中.如果您尚未创建它,则应将其放在 src 文件夹中.

C:\Users\username\Desktop\aureliaApp\src>mkdir components


在此文件夹中,我们将创建 home 关于目录.

C:\Users\username\Desktop\aureliaApp\src\components>mkdir home
C:\Users\username\Desktop\aureliaApp\src\components>mkdir about


主页文件夹中,我们需要创建视图视图模型文件.

C:\Users\username\Desktop\aureliaApp\src\components\home>touch home.js
C:\Users\username\Desktop\aureliaApp\src\components\home>touch home.html


我们还需要查看 view-model for about page.

C:\Users\username\Desktop\aureliaApp\src\components\about>touch about.js
C:\Users\username\Desktop\aureliaApp\src\components\about>touch about.html


注意 : 您也可以手动创建上述所有文件夹.

步骤2  - 页面

接下来,我们需要为我们创建的文件添加一些默认代码.

home.html

<template>
   <h1>HOME</h1>
</template>


home.js

export class Home {}


about.html

<template>
   <h1>ABOUT</h1>
</template>


about.js

export class About {}


第3步 - 路由器

我们将为路由器创建视图模型 app.js 文件中.

app.js

export class App {
   configureRouter(config, router) {
      config.title = 'Aurelia';
		
      config.map([
         { route: ['','home'],  name: 'home',  
            moduleId: './components/home/home',  nav: true, title:'Home' },
         { route: 'about',  name: 'about',
            moduleId: './components/about/about',    nav: true, title:'About' }
      ]);

      this.router = router;
   }
}


我们的路由器视图将放在 app.html .

app.html

<template>
   <nav>
      <ul>
         <li repeat.for = "row of router.navigation">
            <a href.bind = "row.href">${row.title}</a>
         </li>
      </ul>
   </nav>	
   <router-view></router-view>
</template>


当我们运行应用程序时,我们可以通过点击主页或关于链接来更改路线.

Aurelia路由示例