1.路由全局守卫:
router.beforeEach((to, from, next) => {
/* 路由发生变化修改页面title */
if (to.meta.title) {
document.title = to.meta.title
}
next()
})
路由配置:meta中自定义title就行
{
path: '/home',
meta: {
title: 'home'
},
component: () => import('../views/Home.vue')
},
2.利用vue自定义指令:
补充一下vue.config.js配置的方法:此方法一次性修改,用于所有页面公用一个title的情况,
相当于直接修改index.html的title标签,(不过逼格高点 = =)
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
console.log(args);
args[0].title = '自定义title'
return args
})
},
自定义指令方法:main.js加入
Vue.directive('title', {
inserted: function (el, binding) {
document.title = el.dataset.title
}
})
在需要切换title展示的组件中任意一个div中添加v-title data-title="自定义title" 当该组件被调用渲染时title即相应改变,功能和路由全局守卫一致
<div class="left_title" v-title data-title="江山市社会治理中心"></div>