Linux 服务器配置与管理(CentOS Stream 9)
以 CentOS Stream 9(RHEL 9 系)为实验环境的服务器配置与管理课程:从命令行基础、用户权限、磁盘与文件系统,到服务部署、网络与远程管理、安全加固与故障排查。每课时 45 分钟,讲义内附可整段复制粘贴执行的实验命令。
这里是孟凡的课程资料库。内容按「课程项目」分门别类,每一个项目都是一套完整的、 按 45 分钟一课时编排的讲义;每一课时都配了可以下载到本地的课堂练习资料包。 不管你是从头学,还是回头查某一个知识点,都能在这里直接找到。
以 CentOS Stream 9(RHEL 9 系)为实验环境的服务器配置与管理课程:从命令行基础、用户权限、磁盘与文件系统,到服务部署、网络与远程管理、安全加固与故障排查。每课时 45 分钟,讲义内附可整段复制粘贴执行的实验命令。
围绕 Spring、SpringMVC、MyBatis 与 Java Web 项目实践整理的课程讲义与课堂练习。
从 Vue 3 核心语法到 Element Plus 组件实操,按每课时 45 分钟编排的前端实训讲义。每节课配一份可直接粘贴进脚手架 src/App.vue 的完整代码,并提供课堂练习下载包。
以 CentOS Stream 9(RHEL 9 系)为实验环境的服务器配置与管理课程:从命令行基础、用户权限、磁盘与文件系统,到服务部署、网络与远程管理、安全加固与故障排查。每课时 45 分钟,讲义内附可整段复制粘贴执行的实验命令。
围绕 Spring、SpringMVC、MyBatis 与 Java Web 项目实践整理的课程讲义与课堂练习。
从 Vue 3 核心语法到 Element Plus 组件实操,按每课时 45 分钟编排的前端实训讲义。每节课配一份可直接粘贴进脚手架 src/App.vue 的完整代码,并提供课堂练习下载包。
第 30 课你做出了“后台框架 + 子页面”。但马上冒出一个现实问题:任何人只要把地址改成 /admin,就能进后台。 真实系统里,后台、订单、用户资料这些页面必须“先登录、后访问”。
负责这件事的机制叫路由守卫(navigation guard)。它像门口的保安:每一次“要去哪个页面”,都要先过一道检查;不符合条件(比如没登录),就被拦下来、赶到登录页,等登录完再放你回原来想去的地方。
你要知道:登录鉴权是几乎每个正式项目都必备的能力。今天你学会的这套思路,换到 React、换到小程序都通用——本质都是“跳转前先检查身份”。
在上一课的后台基础上加“门禁”:
/ 和 /login 是公开的;/admin 及其子页需要登录,没登录访问会被自动弹到 /login,并且记下“你原本想去哪”;/admin 又会回到登录页;| 做到什么 | 在哪里看 | 完成的证据 |
|---|---|---|
| 未登录进后台被拦 | 访问 #/admin |
自动跳到 #/login 且带 redirect 参数。 |
| 登录后跳回原目标 | 登录页点“登录” | 直接回到被拦前想去的页面。 |
| 退出后凭证失效 | 点“退出登录”再访问 #/admin |
又回到登录页。 |
第 30 课的嵌套路由与 meta 概念(今天在路由上标 requiresAuth)、第 17 课的表单校验思路(登录表单)、第 28 课之前的 localStorage(用来“记住登录状态”)。如果你忘了 localStorage,今天会用一次,正好复习。
| 时间 | 老师带着做 | 学生留下什么 |
|---|---|---|
| 0—6 分钟 | 问“谁能随便改地址进后台?”引出“门禁”需求。 | 理解守卫是“跳转前的检查”。 |
| 6—20 分钟 | 讲 meta.requiresAuth、beforeEach、token 判断、next('/login')。 |
会写“没登录就拦”的逻辑。 |
| 20—30 分钟 | 讲 redirect 查询参数:登录后跳回原目标。 |
理解“记住想去哪”。 |
| 30—40 分钟 | 讲退出登录清 token、afterEach 改标题。 |
会做完整的登录闭环。 |
| 40—45 分钟 | 粘贴本课 App.vue,把三条结果走一遍。 |
全部功能跑通。 |
复制第 30 课的工程,改名 lesson-vue-31。不需要新增依赖——本课继续用手写 hash 路由 + 手写守卫函数演示。
第 32 课讲后台布局菜单 Menu 与面包屑 Breadcrumb:把“门禁后的后台”做成真正像样的后台——左侧菜单高亮、顶部面包屑随路径变、右上角用户下拉。
来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档
| 名字 | 用熟悉的话理解 | 本课里长什么样 |
|---|---|---|
| 路由守卫 | 每次跳转前的“保安检查”。 | 本课 applyRoute 里的拦截逻辑 |
beforeEach |
全局前置守卫:去任何页面前都先过它。 | router.beforeEach((to,from,next)=>{...}) |
meta |
挂在路由上的“附加信息”。 | { meta: { requiresAuth: true } } |
requiresAuth |
“这个页面需要登录”的标记。 | meta.requiresAuth |
| token | 登录后后端发的“门票”,前端存着证明已登录。 | localStorage 里的 demo_token |
next |
守卫里的“放行 / 改道”指令。 | next() 放行、next('/login') 改道 |
redirect(查询参数) |
登录完后“回哪儿”的目标地址。 | ?redirect=/admin/dashboard |
afterEach |
跳转完成后做的事(如改标题)。 | router.afterEach(()=>{ document.title=... }) |
meta 是路由的“标签”你想标记“哪些页面要登录”,最干净的办法是给路由贴个标签,而不是在代码里写一堆 if (path.startsWith('/admin')):
{
path: '/admin',
component: AdminLayout,
meta: { requiresAuth: true }, // 贴个“需要登录”的标签
children: [ /* ... */ ]
}
这一步为什么推荐用 meta:判断逻辑变成“看这个路由有没有 requiresAuth 标签”,而不是“看地址字串”。后者一改名就崩,前者只认标签,路由怎么重组都不怕。
beforeEach 三步曲——检查、放行、改道真实 vue-router 的守卫长这样:
router.beforeEach((to, from, next) => {
const needAuth = to.matched.some(record => record.meta.requiresAuth)
if (needAuth && !store.token) {
next('/login?redirect=' + encodeURIComponent(to.fullPath)) // 改道去登录,并记下目标
} else {
next() // 放行
}
})
to:你要去哪;from:你从哪来;next:放行 / 改道的指令。next:不调用页面就卡住不动(新手最常犯的错)。applyRoute():needAuth && !token 时把 location.hash 改成登录页并带上 redirect。思想完全一样。redirect 参数守卫把“你想去哪”塞进 URL 的 ?redirect=...;登录页登录成功后,读这个参数,跳过去:
// 登录页点登录
const target = route.query.redirect || '/admin/dashboard'
location.hash = '#' + target
这一步为什么重要:用户往往是“先看了一眼后台被弹去登录,登录完就该回到后台”,而不是每次都回首页。把目标地址随 URL 带走,刷新 / 分享都不丢,是最稳的做法。
next()(或本课里忘了改写 location.hash),页面卡住没反应。ref 里,刷新后就没了——应该用 localStorage 持久化。redirect 参数没 encodeURIComponent,目标地址带 ? 或中文会解析错。requiresAuth,结果“登录页也要登录”,死循环。ref 没清 localStorage,刷新后“假性登录”。本课
App.vue把守卫写进了applyRoute()。正式项目请用官方router.beforeEach/afterEach。
src/router/index.js(截取关键):
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
{ path: '/', component: () => import('@/views/Home.vue'), meta: { public: true } },
{ path: '/login', component: () => import('@/views/Login.vue'), meta: { public: true } },
{
path: '/admin',
component: () => import('@/layout/AdminLayout.vue'),
meta: { requiresAuth: true },
redirect: '/admin/dashboard',
children: [
{ path: 'dashboard', component: () => import('@/views/Dashboard.vue') },
{ path: 'users', component: () => import('@/views/UserList.vue') }
]
}
]
const router = createRouter({ history: createWebHashHistory(), routes })
// 全局前置守卫
router.beforeEach((to, from, next) => {
const needAuth = to.matched.some(r => r.meta.requiresAuth)
const token = localStorage.getItem('demo_token')
if (needAuth && !token) {
next('/login?redirect=' + encodeURIComponent(to.fullPath))
} else {
next()
}
})
// 全局后置守卫:改标题
router.afterEach((to) => {
document.title = (to.meta.title || '演示') + ' · 我的项目'
})
export default router
对照一下:本课 applyRoute() 里先判 redirectTo、再判 requiresAuth、最后改 document.title,正好对应 redirect + beforeEach + afterEach 三件事。
来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档
<script setup>
import { ref, computed, h, onMounted, onBeforeUnmount } from 'vue'
import {
ElConfigProvider, ElCard, ElButton, ElAlert, ElMenu, ElMenuItem,
ElInput, ElTag, ElDescriptions, ElDescriptionsItem
} from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'element-plus/dist/index.css'
/* ==================== 假数据 ==================== */
const users = [
{ id: 1, name: '张三', role: '管理员' },
{ id: 2, name: '李四', role: '编辑' }
]
/* ==================== 极简路由树(带 meta 标记,这几十行就是 vue-router 帮你做的事) ==================== */
const routeTree = [
{ path: '/', component: 'Home', meta: { title: '首页', public: true } },
{ path: '/login', component: 'Login', meta: { title: '登录', public: true } },
{
path: '/admin',
component: 'AdminLayout',
meta: { title: '后台', requiresAuth: true }, // 需要登录
redirect: '/admin/dashboard',
children: [
{ path: 'dashboard', component: 'Dashboard', meta: { title: '仪表盘' } },
{ path: 'users', component: 'UserList', meta: { title: '用户' } }
]
}
]
// 把每个组件的 meta 收集起来(子会继承父的 requiresAuth,再被自己的 title 覆盖)
const metaMap = {}
;(function indexMeta(list, parent) {
list.forEach(node => {
metaMap[node.component] = { ...(parent || {}), ...(node.meta || {}) }
if (node.children) indexMeta(node.children, metaMap[node.component])
})
})(routeTree, null)
function parseQuery(str) {
const query = {}
if (!str) return query
str.split('&').forEach(pair => {
if (!pair) return
const eq = pair.indexOf('=')
const k = decodeURIComponent(eq === -1 ? pair : pair.slice(0, eq))
const v = eq === -1 ? '' : decodeURIComponent(pair.slice(eq + 1))
query[k] = v
})
return query
}
function matchPath(path) {
const segs = path.split('/').filter(Boolean)
for (const top of routeTree) {
const topSegs = top.path === '/' ? [] : top.path.split('/').filter(Boolean)
if (topSegs.length === 0) {
if (segs.length === 0) {
if (top.redirect) return { matched: [top.component], params: {}, redirectTo: top.redirect }
return { matched: [top.component], params: {} }
}
continue
}
if (segs.length < topSegs.length) continue
const params = {}
let ok = true
for (let i = 0; i < topSegs.length; i++) {
if (topSegs[i].startsWith(':')) params[topSegs[i].slice(1)] = decodeURIComponent(segs[i])
else if (topSegs[i] !== segs[i]) { ok = false; break }
}
if (!ok) continue
const rest = segs.slice(topSegs.length)
if (!top.children || top.children.length === 0) {
if (rest.length === 0) return { matched: [top.component], params }
continue
}
if (rest.length === 0) {
if (top.redirect) return { matched: [top.component], params: {}, redirectTo: top.redirect }
return { matched: [top.component, 'EmptyChild'], params }
}
for (const child of top.children) {
const childSegs = child.path.split('/').filter(Boolean)
if (childSegs.length !== rest.length) continue
const cparams = {}
let cok = true
for (let i = 0; i < childSegs.length; i++) {
if (childSegs[i].startsWith(':')) cparams[childSegs[i].slice(1)] = decodeURIComponent(rest[i])
else if (childSegs[i] !== rest[i]) { cok = false; break }
}
if (cok) return { matched: [top.component, child.component], params: { ...params, ...cparams } }
}
return { matched: [top.component, 'NotFound'], params }
}
return { matched: ['NotFound'], params: {} }
}
function parseHashString(hashStr) {
const raw = (hashStr || '').slice(1) || '/'
const qIndex = raw.indexOf('?')
const path = qIndex === -1 ? raw : raw.slice(0, qIndex)
const query = parseQuery(qIndex === -1 ? '' : raw.slice(qIndex + 1))
const m = matchPath(path)
return { path, query, ...m }
}
function parseHash() {
return parseHashString(location.hash)
}
/* ==================== 登录态(token) ==================== */
const token = ref(localStorage.getItem('demo_token') || '')
/* ==================== 手写“全局前置守卫 beforeEach” ==================== */
// 真实 vue-router:router.beforeEach((to, from, next) => { ... next() / next('/login') })
function applyRoute() {
const r = parseHash()
// 重定向(默认子路由)
if (r.redirectTo) {
const newHash = '#' + r.redirectTo
currentRoute.value = parseHashString(newHash)
currentHash.value = newHash
location.hash = newHash
return
}
// 守卫核心:需要登录却没有 token → 拦到登录页,并带上“想去哪”
const needAuth = r.matched.some(name => metaMap[name] && metaMap[name].requiresAuth)
if (needAuth && !token.value) {
const target = r.path + (r.query && Object.keys(r.query).length ? '?' + new URLSearchParams(r.query).toString() : '')
const newHash = '#/login?redirect=' + encodeURIComponent(target)
currentRoute.value = parseHashString(newHash)
currentHash.value = newHash
location.hash = newHash
return
}
currentRoute.value = r
currentHash.value = location.hash || '(空)'
// 手写“后置守卫 afterEach”:改标题
const deepest = r.matched[r.matched.length - 1]
const title = (metaMap[deepest] && metaMap[deepest].title) || '演示'
document.title = title + ' · 路由守卫演示'
}
const currentRoute = ref(null)
const currentHash = ref(location.hash || '(空)')
// 先跑一次(首屏也要过守卫)
applyRoute()
onMounted(() => window.addEventListener('hashchange', applyRoute))
onBeforeUnmount(() => window.removeEventListener('hashchange', applyRoute))
function logout() {
token.value = ''
localStorage.removeItem('demo_token')
location.hash = '#/'
}
/* ==================== 页面组件(用 h 写,保证即贴即跑,不依赖运行时编译器) ==================== */
const Home = {
setup() {
const goAdmin = () => { location.hash = '#/admin' } // 没登录会被守卫拦到登录页
const goLogin = () => { location.hash = '#/login' }
return () => h(ElCard, { class: 'block' }, {
header: () => '首页(/,公开)',
default: () => [
h('p', { class: 'muted' }, '点“进入后台”:如果没登录,会被全局前置守卫拦到登录页,并记下你想去的地方(redirect)。'),
h('div', { style: 'display:flex;gap:10px;flex-wrap:wrap;margin-top:8px' }, [
h(ElButton, { type: 'primary', onClick: goAdmin }, '进入后台(/admin,需登录)'),
token.value ? h(ElButton, { type: 'danger', onClick: logout }, '退出登录') : h(ElButton, { onClick: goLogin }, '去登录')
]),
h(ElTag, { style: 'margin-top:12px', type: token.value ? 'success' : 'info' }, token.value ? '已登录' : '未登录')
]
})
}
}
const Login = {
setup() {
const username = ref('')
const password = ref('')
const error = ref('')
const redirect = computed(() => currentRoute.value && currentRoute.value.query.redirect || '')
function doLogin() {
if (!username.value || !password.value) { error.value = '请输入账号和密码'; return }
token.value = 'fake-token-' + Date.now()
localStorage.setItem('demo_token', token.value)
const target = redirect.value || '/admin/dashboard'
location.hash = '#' + target
}
return () => h(ElCard, { class: 'block', style: 'max-width:420px;margin:0 auto' }, {
header: () => '登录(/login,公开)',
default: () => [
redirect.value ? h(ElAlert, { type: 'warning', title: '你被守卫拦截,来自:' + redirect.value, closable: false, showIcon: true, style: 'margin-bottom:10px' }) : null,
h(ElInput, { modelValue: username.value, 'onUpdate:modelValue': v => username.value = v, placeholder: '账号(随便填)', style: 'margin-bottom:10px' }),
h(ElInput, { modelValue: password.value, 'onUpdate:modelValue': v => password.value = v, type: 'password', placeholder: '密码(随便填)', style: 'margin-bottom:10px' }),
error.value ? h(ElAlert, { type: 'error', title: error.value, closable: false, showIcon: true, style: 'margin-bottom:10px' }) : null,
h(ElButton, { type: 'primary', onClick: doLogin }, () => '登录'),
h('p', { class: 'muted', style: 'margin-top:10px' }, '当前 token:' + (token.value || '(未登录)'))
].filter(Boolean)
})
}
}
const Dashboard = {
setup() {
return () => h(ElCard, { class: 'block' }, {
header: () => '仪表盘(/admin/dashboard,需登录)',
default: () => h('p', { class: 'muted' }, '你能看到这一页,说明守卫已经放行(有 token)。')
})
}
}
const UserList = {
setup() {
return () => h(ElCard, { class: 'block' }, {
header: () => '用户(/admin/users,需登录)',
default: () => h(ElDescriptions, { column: 1, border: true, size: 'small' }, {
default: () => users.map(u => h(ElDescriptionsItem, { key: u.id, label: u.name }, () => u.role))
})
})
}
}
const childComponents = { Dashboard, UserList, EmptyChild: null, NotFound: null }
const AdminLayout = {
setup() {
const childName = computed(() => currentRoute.value && currentRoute.value.matched[1])
const childComp = computed(() => childComponents[childName.value])
return () => h('div', { class: 'admin' }, [
h(ElMenu, { mode: 'vertical', defaultActive: '#' + (currentRoute.value && currentRoute.value.path), class: 'admin-menu', onSelect: (idx) => { location.hash = idx } }, {
default: () => [
h(ElMenuItem, { index: '#/admin/dashboard' }, () => '仪表盘'),
h(ElMenuItem, { index: '#/admin/users' }, () => '用户')
]
}),
h('div', { class: 'admin-body' }, [
h('div', { class: 'admin-bar' }, [
h(ElTag, { type: 'success' }, '已登录'),
h(ElButton, { size: 'small', type: 'danger', onClick: logout }, '退出登录')
]),
h(childComp.value || NotFound)
])
])
}
}
const NotFound = {
setup() {
return () => h(ElAlert, { type: 'warning', title: '页面不存在', closable: false, showIcon: true })
}
}
const topComponent = computed(() => {
const name = currentRoute.value && currentRoute.value.matched[0]
return { Home, Login, AdminLayout, NotFound }[name] || NotFound
})
const pageProps = computed(() => (currentRoute.value ? { ...currentRoute.value.params } : {}))
const routeInfo = computed(() => ({
hash: currentHash.value,
matched: currentRoute.value ? JSON.stringify(currentRoute.value.matched) : '—',
token: token.value ? token.value.slice(0, 16) + '…' : '(未登录)',
redirect: (currentRoute.value && currentRoute.value.query.redirect) || '(无)'
}))
</script>
<template>
<el-config-provider :locale="zhCn">
<div class="page">
<h1 class="title">路由守卫与登录鉴权</h1>
<el-alert type="info" :closable="false" show-icon style="margin-bottom:16px">
<template #default>
<div>当前地址栏:<code>{{ routeInfo.hash }}</code></div>
<div>匹配组件链:<b>{{ routeInfo.matched }}</b></div>
<div>当前 token:<b>{{ routeInfo.token }}</b> ,守卫参数 redirect:<b>{{ routeInfo.redirect }}</b></div>
</template>
</el-alert>
<component :is="topComponent" v-bind="pageProps" />
<el-alert
title="要点:① 全局前置守卫 beforeEach 检查 meta.requiresAuth 与 token;② 没登录用 next('/login?redirect=原目标') 跳回;③ 登录后读 redirect 跳回原页;④ afterEach 改标题。"
type="success" :closable="false" show-icon style="margin-top:16px"
/>
</div>
</el-config-provider>
</template>
<style>
html, body, #app {
margin: 0; padding: 0; max-width: none; width: auto; height: auto;
display: block; place-items: initial; text-align: left; background: #f5f7fa;
}
</style>
<style scoped>
.page { max-width: 1000px; margin: 28px auto; padding: 0 16px; }
.title { font-size: 22px; color: #303133; margin: 0 0 18px; }
.block { margin-bottom: 16px; }
.muted { color: #909399; font-size: 13px; }
code { background: #1f2430; color: #a9dc76; padding: 2px 6px; border-radius: 4px; font-size: 13px; }
.admin { display: flex; gap: 16px; align-items: flex-start; }
.admin-menu { width: 180px; min-width: 180px; }
.admin-body { flex: 1; min-width: 0; }
.admin-bar { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; }
</style>
#/login?redirect=%2Fadmin(被守卫拦下),并提示“你被守卫拦截,来自:/admin”。localStorage,地址栏跳回 #/admin/dashboard,显示仪表盘,标题变成“仪表盘 · …”。localStorage 里,刷新后仍是已登录,直接进后台(不会又被弹去登录)。#/;此时再点“进入后台”,又会回到登录页。#/xxx,显示“页面不存在”。为什么“退出登录后刷新”不会再次自动登录,而“登录后刷新”还能保持登录?
因为本课把 token 存在 localStorage 里(不是普通的 ref)。 普通 ref 只活在页面运行期,刷新即清零;localStorage 是浏览器持久化存储,刷新后还在。所以“登录后刷新”能靠 localStorage.getItem('demo_token') 重新读回 token、守卫放行;而“退出登录”时我们 removeItem 把存储也清了,刷新自然读不到。记住这条:要“记住登录状态”,必须落盘到 localStorage(或 sessionStorage / cookie),不能只放内存。
来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档
requiresAuth{ path: '/admin', component: 'AdminLayout', meta: { requiresAuth: true }, ... }
预期:先不加守卫,确认标签已就位。下一步才会真正拦截。
在 applyRoute 里加:
const needAuth = r.matched.some(name => metaMap[name] && metaMap[name].requiresAuth)
if (needAuth && !token.value) {
location.hash = '#/login?redirect=' + encodeURIComponent(r.path)
return
}
预期:没登录访问 /admin,被弹到登录页,地址带 redirect。
redirect 跳回const target = redirect.value || '/admin/dashboard'
location.hash = '#' + target
预期:登录后回到被拦前想去的页面,而不是首页。
localStorage.setItem('demo_token', token.value) // 登录时
localStorage.removeItem('demo_token') // 退出时
预期:刷新后仍能保持登录态(对比只放 ref 会丢)。
afterEach 改标题document.title = (metaMap[deepest].title || '演示') + ' · 路由守卫演示'
预期:切换页面,浏览器标签标题跟着变。
把第 3 页的完整 App.vue 覆盖 src/App.vue,把七条“预期看见什么”全走一遍,尤其验证“刷新是否保持登录”。
| 位置 | 本次作用 |
|---|---|
metaMap |
收集每个路由的 meta(含 requiresAuth)。 |
applyRoute 里的守卫段 |
检查 requiresAuth 与 token,未登录改道登录页。 |
redirect 参数 |
记录“想去哪”,登录后跳回。 |
token(localStorage) |
登录凭证,持久化。 |
logout |
清 token + 跳首页。 |
afterEach 段 |
改 document.title。 |
| 操作或输入 | 预期观察 |
|---|---|
未登录访问 /admin |
跳到 /login?redirect=/admin。 |
| 登录后 | 跳回 /admin/dashboard。 |
| 登录后刷新 | 仍已登录,直接进后台。 |
退出登录再访问 /admin |
又回登录页。 |
| 切页面 | 标题随 meta 变化。 |
访问 #/xxx |
显示“页面不存在”。 |
来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档
requiresAuth。/admin 标 requiresAuth,再给某个子页标 requiresAdmin: true,守卫里额外判断 token 里是否含 admin 角色,否则提示“权限不足”。matched 链暴露给页面,准备第 32 课做面包屑。| 步骤 | 改哪里 | 运行后应该看到什么 |
|---|---|---|
| 1 换区 | routeTree 的需登录路由 |
自己的受保护区。 |
| 2 失败反馈 | Login 的 doLogin |
非 admin 账号被拒。 |
| 3 过期 | 新增“使 token 失效”按钮 | 失效后再访问被拦。 |
| 4 角色 | meta + 守卫判断 |
非 admin 进不了管理页。 |
| 5 面包屑 | 暴露 matched |
为下节课铺垫。 |
| 检查项 | 通过条件 |
|---|---|
| 守卫生效 | 未登录访问受保护区被弹到登录页。 |
| redirect 跳回 | 登录后回到原目标而非首页。 |
| token 持久化 | 登录后刷新仍保持登录。 |
metaMap 构建逻辑,写出“子路由如何继承父的 requiresAuth”。beforeEach 里为什么必须“放行或改道二选一”。提交 src/App.vue 与 练习记录.md。
来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档
| 看到什么现象 / 报错 | 先检查哪里 | 修好后怎样确认 |
|---|---|---|
| 点“进入后台”没反应 / 卡住 | 守卫里没改写 location.hash(相当于没调用 next) |
补上改道逻辑后自动跳登录。 |
| 登录页也弹登录页(死循环) | 登录路由自己也标了 requiresAuth |
登录页改成 public 后正常。 |
| 刷新后变成未登录 | token 只放 ref,没存 localStorage |
存 localStorage 后刷新保持。 |
| 退出登录刷新又“登录”了 | 只清了 ref 没清 localStorage |
两个都清后正常。 |
| redirect 目标解析错(带参数乱码) | 没用 encodeURIComponent |
编码后目标正确。 |
守卫判断 requiresAuth 总为真/总为假 |
metaMap 没建好或 matched 取错 |
修正 meta 收集后正确。 |
| 标题不变 | afterEach(本课 document.title 段)没执行 |
补上后标题随页面变。 |
点后台没反应,是守卫没改道; 登录页也弹登录,是它自己也要登录; 刷新就掉线,是 token 没存盘; 退出还登录,是 localStorage 没清。
console.log 当正式方案。本课是演示;正式项目 token 要设过期时间、必要时用 httpOnly cookie,别把敏感凭证随手放本地。next('/login') 又 next() 两个都调用。守卫里 next 只能调用一次,调两次会报警告甚至死循环。你的 routeTree(含 meta)、你的守卫判断代码、你访问的完整 URL、你的 token 存取位置(localStorage key 名)、实际表现截图。
meta.requiresAuth: true”)?redirect=目标 参数,登录后读它”)来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档
为什么“退出登录后刷新”不会再次自动登录,而“登录后刷新”还能保持登录?
参考解释:token 存在 localStorage,刷新后仍在,所以登录态能恢复;退出时 removeItem 把存储也删了,刷新读不到,自然回到未登录。核心区别在“有没有把凭证落盘”。
| 问题 | 参考解释 |
|---|---|
| 守卫到底在拦什么? | 拦“没登录却想去需登录页”的跳转:检查 meta.requiresAuth 与 token,没有就改道登录页。 |
| 登录后为什么要跳回原目标? | 用户本意是去那个页面,用 redirect 记下目标、登录后读它跳回,体验才顺。 |
| 考考自己 | 可以这样通俗回答 |
|---|---|
| 怎么标记需登录页? | 路由 meta: { requiresAuth: true }。 |
beforeEach 里必须做什么? |
调用 next() 放行,或 next('/login') 改道,且只调一次。 |
| 登录后跳回原页靠什么? | ?redirect=目标,登录页读它。 |
| 为什么 token 用 localStorage? | 刷新后仍在,能记住登录态。 |
afterEach 能做什么? |
跳转完成后改标题、打点统计等。 |
/admin/dashboard 而非首页。src/App.vue 与 练习记录.md 已保存。把本课手写的守卫(applyRoute 里的拦截段)和正式 router.beforeEach 逐行对照:写下一句话,你觉得手写守卫最容易在哪漏掉一步?为什么 next 只能调用一次这件事值得专门记?
来源:本课自编 Vue 3 前端核心技能实训 · 语法依据 Vue 3.5 官方文档 · 组件依据 Element Plus 2.8 官方文档