Angular4 第三章(中) 重定向路由,子路由,辅助路由
程序员文章站
2022-03-24 19:12:51
...
1.重定向路由配置
const routes:Routes = [
{path:'', redirectTo: '/home', pathMatch:'full'},
{path:'home', component: HomeComponent }, // 默认展示HomeComponnet
{path:'**', component: Code404Component}
];
pathMatch:'full' 访问路径精准
2.子路由
前提:生成两个组件BuyerListComponent,SellerListComponent,将这两个组件显示在股票详情组件之内。
const routes: Routes = [
{path: '', redirectTo: '/home', pathMatch: 'full'},
{path: 'home', component: HomeComponent },
{
path: 'stock/:id', component: StockComponent, data: [{isPro: true}],
children: [
{path: '', component: BuyerListComponent},
{path: 'seller/:id', component: SellerListComponent}
],
},
{path: '**', component: Code404Component}
];
在股票详情模板中
<div class="stock">
<p>
stock works!这里是股票详情
</p>
<p>股票stock.id是{{stock.id}}</p>
<p>股票名称{{stock.name}}</p>
<p>isPro是{{isPro}}</p>
<p>
<input type="button" (click)="focus=true" value="关注" />
</p>
<a [routerLink]="['./']">买家信息</a>
<a [routerLink]="['./seller',100]">卖家信息</a>
<router-outlet></router-outlet>
</div>
注意 (1)子路由可以无限级的嵌套的
(2)一个组件可以是一个主组件,也可以是子组件
3.辅助路由
(1)声明一个辅助路由,需要三步:
step1 :
在组件模板上声明一个主插座,和一个带有name属性的插座,如下所示:
<router-outlet></router-outlet> 主插座
<router-outlet name="aux"></router-outlet> 辅助插座
step2:
在路由配置上需要配置这个叫“aux”的插座可以显示哪些组件,如下:
{path:'xxx',component:XxxComponent,outlet:'aux'}
{path:'yyy',component:YyyComponent,outlet:'aux'}
step3:
在路由导航时,在路由到某一个地址时,
<a [routerLink]="['/home',{outlets:{aux:'xxx'}}]">Xxx</a>
<a [routerLink]="['/product',{outlets:{aux:'yyy'}}]">yyy</a>
注解:
<router-outlet></router-outlet>显示‘/home’对应的组件,
<router-outlet name="aux"></router-outlet> 显示xxx组
(2)举例实现辅助路由
思路:
一:在app组件的模板上再定义一个插座来显示在线咨询组件
二:单独开发一个在线咨询组件,只显示在新定义的插座上
三:通过路由参数控制新的辅助插座是否显示在线咨询组件
开始:
A 实现思路一: 在app.component.html
<a [routerLink]='["/home"]'>主页</a>
<a [routerLink]='["/stock",1]' >股票详情</a>
<input type="button" value="股票详情" (click)="toStockDetail()" />
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
B 生成新的咨询组件 consult首先,consult.component.html中:
<textarea placeholder="请输入咨询问题" class="consult"></textarea>
其次配置路由:{path: 'consult', component: ConsultComponent, outlet: 'aux'},
C 在app.component.html加入:
<a [routerLink]='["/home"]'>主页</a>
<a [routerLink]='["/stock",1]' >股票详情</a>
<input type="button" value="股票详情" (click)="toStockDetail()" />
<a [routerLink]="[{outlets:{aux:'consult'}}]">开始咨询</a>
<a [routerLink]="[{outlets:{aux:null}}]">结束咨询</a>
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
此时,完成实现辅助路由补充
<a [routerLink]="[{outlets:{primary:'home'aux:'consult'}}]">开始咨询</a>
点击开始咨询主路由跳到home组件上上一篇: vue中路由重定向
下一篇: 剪映搜索在哪里?剪映怎么搜索视频