第五节:Vue‑Router4 路由配置,布局嵌套路由
仿若依设计:
- 登录页面独立路由,不套 Layout
- 后台页面全部嵌套在 Layout 布局下
- 拆分常量路由,后续预留动态路由位置;全部使用 setup 语法,路由懒加载
步骤 1:新建登录页面
新建 src/views/login/index.vue
c
<template>
<div class="login-container">
<el-card style="width:420px;margin:100px auto;">
<h2 style="text-align:center;margin-bottom:20px;">系统登录</h2>
<el-form>
<el-form-item label="账号">
<el-input v-model="loginForm.username"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="loginForm.password" type="password"></el-input>
</el-form-item>
<el-button type="primary" style="width:100%" @click="handleLogin">登录</el-button>
</el-form>
</el-card>
</div>
</template>
<script setup>
const loginForm = reactive({
username: '',
password: ''
})
const handleLogin = () => {
console.log('登录表单', loginForm)
// 暂时只打印,登录逻辑后面axios章节完善
}
</script>
<style scoped>
.login-container {
background-color: #f5f7fa;
min-height: 100vh;
}
</style>
步骤 2:完善路由 src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
// 布局组件
const Layout = () => import('@/layout/index.vue')
// 常量路由:所有人都可以访问
export const constantRoutes = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: () => import('@/views/login/index.vue')
},
{
path: '/404',
component: () => import('@/views/error/404.vue')
}
]
// 嵌套布局路由,后台菜单页面都写在这里
export const asyncRoutes = [
{
path: '/dashboard',
component: Layout,
redirect: '/dashboard/index',
children: [
{
path: 'index',
name: 'Dashboard',
component: () => import('@/views/dashboard/index.vue'),
meta: { title: '首页看板' }
}
]
}
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [...constantRoutes, ...asyncRoutes]
})
export default router
步骤 3:新建需要的占位页面
-
src/views/error/404.vue404 页面不存在
返回登录 -
src/views/dashboard/index.vue(后台首页)后台首页 Dashboard
-
修改
src/layout/index.vue,必须增加<router‑view>用于渲染子路由Layout主布局容器
✅第五节测试
- 重启
pnpm dev - 浏览器访问:
/login→ 正常展示登录表单页面 ✔/dashboard/index→ 看到 Layout 容器 + 后台首页卡片 ✔/xxx随便写→ 跳 404 页面(注意:我们还没写全局路由守卫,直接访问不存在路径才会到 404)
- F12 控制台无报错。
注意:现在访问
/dashboard/index不需要登录校验,路由守卫后面再补充。


