DAY26 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (下)

這一篇筆記結束後,有關 Vue Router 基礎就先告一段落了,之後應該會來寫 Vue 的圖書館 Vuex 的筆記。

重定向和別名

重定向和別名都是作用在 routes 物件上,只不過用途有些許不同。

重定向(redirect)

簡單來說,就是要連到 A 位址並顯示 A 模組,但因遇到某些問題,想讓可點選 A 連結的地方全部重新導向 B 連結,這時候就可以透過 redirect 這個方法,直接讓點選 A 連結的地方都導向 B 連結,並顯示 B 模組。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//1.創建路由(創建模組及命名)
const HOME = {
template: `<div style="background:yellow;color:black">
<p>HOME</p>
</div>`,
created() {
console.log(this.$route.path);
}
};

const ABOUT = {
template: `<div style="background:blue;color:white">
<p>ABOUT</p>
</div>`,
created() {
console.log(this.$route.path);
}
};

//2.定義路由
//原本導向 /home 的地方,全都導向 /about ,不只是網址改變而是連顯示的模組都變成 /about 會顯示的模組
const routes = [
{ path: "/home", component: HOME, redirect: "/about" },
{ path: "/about", component: ABOUT }
];

//3. 創建 router 實例
const router = new VueRouter({
routes
});

別名(alias)

就是綽號的意思,就像是一個人擁有綽號後,當別人喊這個綽號時,你自然會知道是在叫你。

當我們給予路徑 A 一個綽號(alias)後,透過點選這個綽號,我們同樣可以連結到路徑 A 。

1
<router-link to="/profile">Go to ABOUT</router-link>
1
2
3
const routes = [
{ path: "/about", component: ABOUT, alias: "/profile" }
];

/profile 就是 /about 的別名,也因此 <router-link to="/profile"> 同樣會使用 ABOUT 模組。

路由模組傳參數

之前在頁面上顯示路由參數都是透過訪問 $route 取得的,但 Vue Router 還有一種方式可以取得路由參數,那就是透過 props

原本取得參數的方法

1
<router-link to="/user/celeste?search=michelle">Celeste</router-link>
1
2
3
4
5
6
7
8
9
const User = {
template:`<div>
<p>{{ $route.params.id }}</p>
<p>{{ $route.query.search }}</p>
</div>`
}
const routes = [
{ path: "/user/:id", component: User }
];

透過 props 取得參數

1
<router-link to="/user/celeste?search=michelle">Celeste</router-link>
1
2
3
4
5
6
7
8
9
10
const User = {
props: ['id', 'search'],
template:`<div>
<p>{{ id }}</p>
<p>{{ search }}</p>
</div>`
}
const routes = [
{ path: "/user/:id", component: User, props:true }
];

這時候會發現 Query 的參數並無法顯示,所以如果有其他參數要做為 props 資料顯示的話,可以透過函數的方式取得。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const User = {
props: ['id', 'search'],
template:`<div>
<p>{{ id }}</p>
<p>{{ search }}</p>
</div>`
}
const routes = [
{ path: "/user/:id",
component: User,
props: route => {
return {id: route.params.id, search: route.query.search}
}
}
];

Demo

See the Pen DAY26 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (下) by Celeste6666 (@celeste6666) on CodePen.

參考資料

Vue Router - 重定向和别名

Vue Router - 路由组件传参