vue3使用vue-router嵌套路由(多级路由)
在Vue 3中,使用Vue Router进行嵌套路由,你需要定义路由的层级结构,在路由配置中使用children属性来定义嵌套路由。以下是一个简单的例子:
首先安装Vue Router:
npm install vue-router@4
然后配置你的路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
import Dashboard from './views/Dashboard.vue'
import Settings from './views/Settings.vue'
// 定义路由
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About,
children: [
{
path: '',
redirect: 'dashboard'
},
{
path: 'dashboard',
name: 'Dashboard',
component: Dashboard
},
{
path: 'settings',
name: 'Settings',
component: Settings
}
]
}
]
// 创建路由实例
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
在你的main.js
或main.ts
文件中引入并使用路由:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
在About.vue
组件中,你可以使用<router-view>
来渲染嵌套的视图:
<template>
<div>
<h1>About Page</h1>
<router-view />
</div>
</template>
现在,当你导航到/about
时,Dashboard
组件将被渲染在About
页面的<router-view>
中。访问/about/settings
将渲染Settings
组件。这就是如何在Vue 3中使用Vue Router进行嵌套路由的简单示例。
评论已关闭