DAY26 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (下)
這一篇筆記結束後,有關 Vue Router 基礎就先告一段落了,之後應該會來寫 Vue 的圖書館 Vuex 的筆記。
重定向和別名
重定向和別名都是作用在 routes
物件上,只不過用途有些許不同。
重定向(redirect
)
簡單來說,就是要連到 A 位址並顯示 A 模組,但因遇到某些問題,想讓可點選 A 連結的地方全部重新導向 B 連結,這時候就可以透過 redirect
這個方法,直接讓點選 A 連結的地方都導向 B 連結,並顯示 B 模組。
1 | //1.創建路由(創建模組及命名) |
別名(alias
)
就是綽號的意思,就像是一個人擁有綽號後,當別人喊這個綽號時,你自然會知道是在叫你。
當我們給予路徑 A 一個綽號(alias
)後,透過點選這個綽號,我們同樣可以連結到路徑 A 。
1 | <router-link to="/profile">Go to ABOUT</router-link> |
1 | const routes = [ |
/profile
就是 /about
的別名,也因此 <router-link to="/profile">
同樣會使用 ABOUT 模組。
路由模組傳參數
之前在頁面上顯示路由參數都是透過訪問 $route
取得的,但 Vue Router 還有一種方式可以取得路由參數,那就是透過 props
。
原本取得參數的方法
1 | <router-link to="/user/celeste?search=michelle">Celeste</router-link> |
1 | const User = { |
透過 props
取得參數
1 | <router-link to="/user/celeste?search=michelle">Celeste</router-link> |
1 | const User = { |
這時候會發現 Query 的參數並無法顯示,所以如果有其他參數要做為 props
資料顯示的話,可以透過函數的方式取得。
1 | const User = { |
Demo
See the Pen DAY26 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (下) by Celeste6666 (@celeste6666) on CodePen.
參考資料