---
# System prepended metadata

title: Vue Router「引用 &切換頁面」(7-1)
tags: [7. Router路由, Vue]

---

# Vue Router「引用 &切換頁面」(7-1)
###### tags: `Vue`、`7. Router路由`
2022.3.9

&emsp;&emsp;Router路由，為Serve與Controller中間的溝通媒介。工作內容主要是聽從server提出的要求，並因應此要求向Controller轉達需要甚麼頁面元件，最後Controller再完成任務。啟用Router會再網址後加 #。

![](https://i.imgur.com/ulMjttm.png)

### 1. 引用Vue Router 
```
// 需先引入VueRouter CDN
<script src="https://unpkg.com/vue-router@4.0.5/dist/vue-router.global.js"></script>

<script>
    const app = Vue.createApp({
        data(){
            return{
                text:'Vue Router 引入'
            } 
        },
    });

    const router = VueRouter.createRouter({
        history: VueRouter.createWebHashHistory(),
        routes:[]
    })
    
    app.use(router);
    app.mount('#app');
</script>
```
**成功畫面**

![](https://i.imgur.com/Hyo0pvw.png)

### 2. 渲染到網頁(網頁切換，A、B兩頁面切換)
```
// 需先引入VueRouter CDN
<script src="https://unpkg.com/vue-router@4.0.5/dist/vue-router.global.js"></script>

<div id='app'>
    <p><h1>{{ text }}</h1></p>
    <h1>
        <router-link to='/a'>A頁面</router-link> |
        <router-link to='/b'>B頁面</router-link>
        <router-view></router-view>
    </h1>
</div>

<script>
const A_component = {template:`<h2>頁面A</h2>`};
const B_component = {template:`<h2>頁面B</h2>`};

const app = Vue.createApp({
    data(){
        return{
            text:'Vue Router頁面切換'
        }
    }
});

const router = VueRouter.createRouter({
    history:VueRouter.createWebHashHistory(),
    routes:[
        {
            path:'/a',
            component:A_component
        },
        {
            path:'/b',
            component:B_component
        }
    ]
});

app.use(router);
app.mount('#app');
</script>
```