Ionic4+Angular跨模块路由使用ion-tabs的问题与解决
嘿,我来帮你搞定这个标签栏全激活的问题,顺便聊聊跨模块路由下用标签栏的正确姿势~
首先说你遇到的全标签激活的问题:
你直接给ion-tab-button加routerLink的思路是对的,但问题出在路由匹配的逻辑上。默认的routerLinkActive是前缀匹配——比如当你在/content/dashboard页面时,/content开头的两个标签都会被判定为“匹配”,再加上你没指定激活状态对应的样式类,就导致所有标签都显示激活了。
解决方法很简单,给每个ion-tab-button加上这两个配置:
routerLinkActive="tab-selected":指定Ionic标签按钮激活时的样式类(Ionic默认用这个类来控制选中状态的样式)[routerLinkActiveOptions]="{ exact: true }":开启精确路由匹配,只有当当前路由和routerLink完全一致时,才会激活这个标签
修改后的代码如下:
<ion-tabs> <ion-tab-bar slot="bottom"> <ion-tab-button routerLinkActive="tab-selected" [routerLinkActiveOptions]="{ exact: true }" [routerLink]="['/', 'content', 'dashboard']" > <ion-label>Home</ion-label> <ion-icon name="home"></ion-icon> </ion-tab-button> <ion-tab-button routerLinkActive="tab-selected" [routerLinkActiveOptions]="{ exact: true }" [routerLink]="['/', 'content', 'explore']" > <ion-label>Explore</ion-label> <ion-icon name="search"></ion-icon> </ion-tab-button> <ion-tab-button routerLinkActive="tab-selected" [routerLinkActiveOptions]="{ exact: true }" [routerLink]="['/', 'user']" > <ion-label>Profile</ion-label> <ion-icon name="person"></ion-icon> </ion-tab-button> </ion-tab-bar> </ion-tabs>
接下来聊跨模块路由使用标签栏的正确方式:
标签栏属于应用的全局导航,最好放在一个布局外壳组件里(比如LayoutComponent或者直接用AppComponent),这个组件要包含<router-outlet>,所有需要显示标签栏的页面,都作为这个布局组件的子路由。
具体步骤:
创建布局组件
模板里同时放标签栏和路由出口,这样切换路由时,内容在router-outlet里渲染,标签栏始终留在页面底部:<!-- layout.component.html --> <ion-tabs> <ion-tab-bar slot="bottom"> <!-- 你的标签按钮代码 --> </ion-tab-bar> </ion-tabs> <router-outlet></router-outlet>配置根路由
在app-routing.module.ts里,把需要显示标签栏的路由都作为布局组件的子路由,同时配置懒加载各个模块:const routes: Routes = [ // 全局布局路由,包含标签栏 { path: '', component: LayoutComponent, children: [ { path: 'content/dashboard', loadChildren: () => import('./content/content.module').then(m => m.ContentModule) }, { path: 'content/explore', loadChildren: () => import('./content/content.module').then(m => m.ContentModule) }, { path: 'user', loadChildren: () => import('./user/user.module').then(m => m.UserModule) }, ] }, // 不需要显示标签栏的路由(比如登录页),直接放在根路由下 { path: 'login', component: LoginComponent }, ];配置模块内的路由
每个模块的路由要对应根路由的子路径,比如:content-routing.module.ts里配置子路由:const routes: Routes = [ { path: 'dashboard', component: DashboardComponent }, { path: 'explore', component: ExploreComponent }, ];user-routing.module.ts里配置根路径(因为根路由里是/user,所以这里path为空):const routes: Routes = [ { path: '', component: UserComponent }, ];
这样配置后,标签栏就能稳定地链接不同模块的路由,同时激活状态也能正确显示啦~
内容的提问来源于stack exchange,提问作者Yulian
相关产品推荐
相关产品推荐

