最基本的寫法就是在 src/router/index.ts 的 routes 內設定像這樣
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'home',
component:()=>import('@/components/home.vue')
},
{
path: '/about',
name: 'about',
component:()=>import('@/components/about.vue')
}
]
path 是設定路由,name 如果你沒有要用路由傳參,不寫也沒關係,component 是對應到哪個你寫的 vue 頁面
跟 <a></a> 很像,用法是像
<router-link to="/">Home</router-link>
設定 to="路由" 就可以在頁面上點這個連結進入想去的頁面
這是一個很重要的技術,現在大部分的網頁都是至少由兩個頁面組成,一個父頁面和一個子頁面。什麼意思呢?就是你現在隨便進一個網站,然後去不同頁面,你有沒有發現最上面的導覽列都長一樣?原理就是想要每一頁都出現的東西寫在父頁面,然後每一頁要不同的東西寫在子頁面。
只要在 src/router/index.ts 內的 routes 設定像這樣
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('../components/parent.vue'), // 父頁面
// 以下是子頁面 ###########################################
children:[
{
path: '/',
name: 'home',
component: ()=>import('@/components/home.vue')
},
{
path: '/children',
name: 'children',
component: ()=>import('@/components/children.vue')
},
]
},
]
加上一個 children 屬性,然後 children 設定路由,現在根路由及 /children 都會套用 parent.vue 了
那回到 .vue file,那要怎麼設定子頁面出現在父頁面的什麼位置呢?其實官方在 App.vue 已經有示範了

就是在父頁面寫一個 <router-view/> 就是代表子頁面要長在這個位置
我們可以透過 url 傳遞參數,就是像這樣
{
path: '/:year/:month',
name: 'home',
component: ()=>import('@/components/home.vue')
},
用 :year, :month 就可以設定有一個參數是 year,然後有一個參數是 month,所以你如果進入 /2022/09 這個路由,那這個頁面就有一個參數叫 year 然後值等於 "2022",有一個參數叫 month 然後值等於 "09"
那在 vue 頁面中要怎麼使用由路由傳遞的參數呢
<script lang="ts" setup>
import { useRoute } from 'vue-router'
const route = useRoute()
let year=route.params['year']
</script>
先從 vue-router 中引入 useRoute,然後用令一個變數等於 useRoute().params['year'],就可以使用 year 這個參數
useRouter 用來進入其他路由
<script lang="ts" setup>
import { useRouter } from 'vue-router'
const router = useRouter()
router.push('/')
</script>
引入 useRouter,然後 useRouter().push('路由') 就行了
再來做一個 404 頁面,在 routes 設定的最後一個元素這樣寫
{
path: "/:pathMatch(.*)*",
component: () => import("../components/404.vue"),
}
這是說如果你輸入的路由都沒有符合以上的路由的話就導入你寫的 404 頁面