vue 设置动态标题
在 router/index.js 文件中设置 meta:{title:'标题'} 和 router.beforeEach,即可实现功能, 代码如下:
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path: "/",
name: "login",
component: ()=> import("@/views/LoginView") ,
meta:{title:'登录',keepAlive:false}
},
{
path: "/home",
name: "home",
component: ()=> import("@/views/HomeView"),
meta:{title:'首页',keepAlive:false}
}
];
const router = createRouter({
history: createWebHashHistory(),
routes,
});
// 路由守卫
router.beforeEach((to,from ,next)=>{
if(to.meta.title) {
document.title=to.meta.title;
}else {
document.title='vue-demo';
}
next()
})
export default router;