前言

除了使用Router的navigate()方法切换路由,Angular2还提供了一个指令用来 将一个DOM对象增强为路由入口:

@View({
directives:[RouterOutlet,RouterLink]
template : `<nav>
<b router-link="video">video</b> | 
<b router-link="music">music</b>
</nav>
<router-outlet></router-outlet>`
}) 

RouterLink指令为宿主DOM对象添加click事件监听,在触发时调用Router的 navigate()方法进行路由。

不过本文主要介绍的是关于Angular之RouterLink花式跳转的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

routerLink本身支持两种写法:

<a routerLink="detail">
</a>

<a [routerLink]="['detail']">
</a>

routerLink的值有哪些写法,又有什么区别呢?

假设当前路由为

`http://localhost:4200/#/doc/license`

写法1 : 绝对路径  / + 路由名字

 <!--跳到 http://localhost:4200/#/doc/license -->
 <a [routerLink]="['/doc/demo']" >跳呀跳</a>
 
 <!--跳到 http://localhost:4200/#/demo -->
 <a [routerLink]="['/demo']" >跳呀跳</a>

那么url是

http://localhost:4200/#/doc/demo上跳转,即 http://localhost:4200/#/ + 你要跳转的绝对路径。

写法2 : 一个路由名字 路由名字

 <a [routerLink]="['demo']" >跳呀跳</a>

那么url是http://localhost:4200/#/doc/license/(demo),即http://localhost:4200/#/doc/license + 你要跳转的绝对路径,这时候它会给你的路由加些东西变成 /(demo),跳转不了。

写法3 :相对路径 ../路由名字

 <a [routerLink]="['../demo']" >跳呀跳</a>

那么url是

http://localhost:4200/#/doc/demo,即 http://localhost:4200/#/doc + 你要跳转的相对路径。它会从上一级开始寻找。

写法4  : ./路由名字, 即现在的路由+你写的要跳去的路由

 <a [routerLink]="['./demo']" >跳呀跳</a>

那么url是

http://localhost:4200/#/doc/license/demo上,即 http://localhost:4200/#/doc/license + 你要跳转的相对路径。它会从当前路由的下一级开始寻找此匹配的路由进行跳转。

| 更多API用法更新于 github

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对悠悠之家的支持。

点赞(111)

评论列表共有 0 条评论

立即
投稿
返回
顶部