Vue如何根据不同的路由设置不同的title标题
作者:Sunshine_Jian
本文主要介绍了如何在Vue路由中添加meta属性,并以及使用router.beforeEach编写路由前置守卫,以实现在路由跳转前的一些操作,并详细地给出了代码示例
第一步
在router>index.js文件中编写路由规则,并增加meta属性;
{
path:'/billSystem',
name:'bill_system',
component:() => import('../views/bill_system/index.vue'),
meta:{
title:'账单管理',
keepAlive:false
}
},第二步
在路由规则下方,增加路由前置守卫,router.beforeEach
to:即将进入的路由信息对象(去哪里)from:离开的路由信息对象(从哪里来)next():放行(当前路由继续执行)
//路由前置守卫;用来设置元信息
router.beforeEach((to,from,next)=>{
if(to.meta.title){
document.title=to.meta.title
}
next()
})效果


最后:呈上所有代码
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
redirect:'/dashBoard',
component: () => import('../views/Home.vue'),
children:[
{
path:'/dashBoard',
name:'dash_board',
component:() => import('../views/dash_board/index.vue'),
meta:{
title:'首页',//配置title
keepAlive:false,//是否缓存
requireAuth:false//是否需要身份验证
}
},
{
path:'/accountInfo',
name:'account_info',
component:() => import('../views/account_info/index.vue'),
meta:{
title:'账户信息',
keepAlive:false,
requireAuth:false
}
},
{
path:'/billSystem',
name:'bill_system',
component:() => import('../views/bill_system/index.vue'),
meta:{
title:'账单管理',
keepAlive:false,
requireAuth:false
}
},
{
path:'/applicationInfo',
name:'application_info',
component:() => import('../views/application_info/index.vue'),
meta:{
title:'应用数据',
keepAlive:false,
requireAuth:false
}
},
{
path:'/userSystem',
name:'user_system',
component:() => import('../views/user_system/index.vue'),
meta:{
title:'用户管理',
keepAlive:false,
requireAuth:false
}
}
]
}
]
const router = new VueRouter({
routes
})
//路由前置守卫;用来设置元信息
router.beforeEach((to,from,next)=>{
if(to.meta.title){
document.title=to.meta.title
}
next()
})
export default router
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
