大家好今天是鐵人賽的第20天唷!
前一天文章,介紹了vue-router的基本用法。
今天要多說一些用法:
命名路由允許你為路由定義一個名稱,以便在程式中進行引導。例如:
const routes =
[
    {
        path: '/user/:id',
        name: 'User',
        component: User
    }
]
上述路由,我們的路徑為/user/:id定義一個名稱為'User'的路徑,現在可以在元件中用這個名稱來進行導航:
<template>
    <div>
        <router-link :to="{ name: 'User', params: { id: 1 } }">User 1</router-link>
        <router-link :to="{ name: 'User', params: { id: 2 } }">User 2</router-link>
    </div>
</template>
vue-router支援路由嵌套,讓你在這個元件中嵌套另一個元件的路由,建立複雜頁面佈局時非常有用,你可以有一個包含多個子頁面的主頁:
const routes =
[
    {
        path: '/dashboard',
        component: Dashboard,
        children:
        [
            {
                path: 'overview',
                component: Overview
            },
            {
                path: 'stats',
                component: Stats
            }
        ]
    }
]
上述程式碼Dashboard元件包含了兩個子頁面:Overview和Stats,可以在Dashboard元件中使用來渲染子頁面。
除了使用router-link進行導航,還可以使用編程式導航在JS中導航,vue-router提供router對象,也可以使用它來進行導航操作:
// 組件中
methods: {
    goToUser(id) {
        this.$router.push({ name: 'User', params: { id } })
    }
}
// 在全局
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
    history: createWebHistory(),
    routes
})
router.push('/about') // 導航到/about
今天的內容就到這囉~我們明天見~![]()