因为在vue项目中只有一个index.html文件,title显示需要通过vue-router来设置;
1、在router文件夹index.js文件中添加meta属性
export default new Router({
// mode: 'history',
routes: [
{
path: '/',
name: 'Home',
component: Home,
meta: {
title: '首页'
}
},{
path:'/productList',
name:'productList',
component:productList,
meta: {
title: '产品列表'
}
},{
path:'/roleManagement',
name:'roleManagement',
component:roleManagement,
meta: {
title: '角色管理'
}
}]
})
2、在router文件夹index.js文件中,在每一个meta里面设置页面的title名字,最后在遍历
router.beforeEach((to, from, next) => {
/* 路由发生变化的时候进行页面title的修改 */
// 这个方法是为了每个页面添加属于自己的title
router.beforeEach((to, from, next) => {
//路由发生变化修改页面title
if (to.meta.title) {
document.title = to.meta.title
}
next()
})
3、知识点拓展
(1)vue.beforEach(function(to,form,next){})//路由跳转之前执行
beforeEach函数有三个参数:
- to:router即将进入的路由对象
- from:当前导航即将离开的路由
- next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
4、完整例子
// 引入vue模块
import Vue from 'vue'
// 引入路由模块
import Router from 'vue-router'
// 引入登录组件
import Home from '@/pages/Home/Home.vue'
import productList from '@/pages/productList/productList.vue'
import roleManagement from '@/pages/roleManagement/roleManagement.vue'
Vue.use(Router)
// 定义路由实例
const router = new Router({
mode: 'history',
routes: [{
path: '/home',
name:'Home',
component:Home,
meta: {
title: '首页'
}
},
{
path: '/productList',
name: 'productList',
component: productList,
meta: {
title: '产品列表'
}
},
{
path: '/roleManagement',
name: 'roleManagement',
component: roleManagement,
meta: {
title: '角色管理'
}
},
]
})
// 这个方法是为了每个页面添加属于自己的title
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title
}
next()
})
// 将路由实例暴露出来
export default router