先在路由界面给每个页面赋值一个meta的title属性,将每个页面都有一个自带的title存放界面名称
import {
createRouter as _createRouter,
createWebHashHistory,
} from 'vue-router'
// import index from "~/pages/index.vue"
import Home from "~/pages/home/home.vue"
import Login from "~/pages/login/login.vue"
//新增如下:
const routes = [
{
path: "/home",
component: Home,
//这里写的是每个页面的标题
meta:{
title:"后台首页"
}
},
{
path:"/",
component:Login,
//这里写的是每个页面的标题
meta:{
title:"登录页面"
}
},
//404页面捕获
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('~/pages/404.vue'),
//这里写的是每个页面的标题
meta:{
title:"404"
}
},
]
//这里有错误,不知道什么原因只能使用函数返回,直接定义会报错
function createRouter() {
return _createRouter({
history: createWebHashHistory(),
routes
})
}
//创建路由
const router = createRouter()
export default router
然后我们就可以在路由前置守卫中拿每个页面的标题了。
//处理权限验证相关的东西
import router from '~/router'
import { toast, showFullLoading, hideFullLoading } from '~/composables/util.js'
import { getToken } from '~/composables/auth'
import store from './store'
//全局前置守卫
router.beforeEach(async (to, from, next) => {
// console.log(from);
//显示loading
showFullLoading()
const token = getToken()
//如果没有登录强制跳转会登录页
if (!token && to.path != "/") {
toast("请先登录", "error")
return next({ path: "/" })
}
//防止重复登录
if (token && to.path == "/") {
toast("请勿重复登录", "error")
return next({ path: from.path ? from.path : "/" })
}
//判断用户是否登录,自动获取用户信息,并存储在vuex中
if (token) {
//异步
await store.dispatch("getinfo")
}
//设置页面的标题
// console.log(to.meta.title);
let title = (to.meta.title ? to.meta.title:"") + "LLT"
document.title = title
next();
// console.log("全局前置守卫");
});
//全局后置守卫
router.afterEach((to, from) => {
console.log(to, from);
hideFullLoading()
})
bingou结束