---
# System prepended metadata

title: 【VUE】Router
tags: [VUE]

---

---
tags: VUE
---
【VUE】Router
===
[說明文件](https://router.vuejs.org/zh/)

```
1. 進入點
main.js

2. Router配置檔
@/router/index.js

3. 分頁內容
Vue.components (***.vue)
```

### 1. router配置檔
- @/router/index.js
```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
// 官方的元件

import Home from '@/components/HelloWorld'
// 自訂的分頁元件

Vue.use(VueRouter)

export default new VueRouter({
    routes: [
        {
            name: '',  // 元件呈現的名稱
            path: '',  // 對應的虛擬路徑
            component:  // 對應的元件
        }  
    ]
})
```
- @/main.js

```javascript=
import router from './router'
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  router
})
```

### 2. 巢狀router
- router/index.js
```javascript
import Page from '@/components/pages/page'
import child from '@/components/pages/child'
import child2 from '@/components/pages/child2'
import child3 from '@/components/pages/child3'

export default new Router({
    routes: [
        {
            name: '首頁',  // 元件呈現的名稱
            path: '/index',  // 對應的虛擬路徑
            component: Home // 對應的元件
        },      
        {
            path: '/page',
            component: Page,
            children: [
                {
                    name: '卡片1',
                    path: '', 
                    component: child 
                },
                {
                    name: '卡片2',
                    path: 'child2', 
                    component: child2 
                },
                {
                    name: '卡片3', 
                    path: 'child3', 
                    component: child3
                },
            ]
        }      
    ]
})
```

### 3.同一個路徑載入多個元件

```htmlmixed=
<router-view name="menu"></router-view>
<router-view></router-view>
```
- router/index.js
```javascript=
import Page from '@/components/pages/page'
import Menu from '@/components/pages/menu'
components: {
    default: Page,
    menu: Menu
},
```

### 4. class name替換
```javascript=
// router/index.js
linkActiveClass: 'active'
```

### 5. 自定義切換路由
https://router.vuejs.org/zh/api/#router-aftereach
```htmlmixed=
<li class="nav-item">
    <a href="#" class="nav-link" @click.prevent="updatePath">切換到指定頁面</a>
</li>
<li class="nav-item">
    <a href="#" class="nav-link" @click.prevent="beforePath">回到前面</a>
</li>
```
```javascript=
// menu元件
methods: {
    updatePath() {
        this.$router.push('/page/child2');
    },
    beforePath() {
        this.$router.back();
    }
}
```