方法一:
第一步:在main.js里面添加一个全局指令
Vue.directive(‘title’, {
inserted: function (el, binding) {
document.title = el.dataset.title
}
})
第二步:在要调用的组件里面,随便找一个div加入如下代码
v-title data-title=“我的”
<template>
<header class="header_home user_reg" v-title data-title="">
<div class="top_box hidden-xs">
<div class="container">
<router-link to="/" class="logo">
<img src="../../../assets/image/5b10f166c3332.png" alt="" />
</router-link>
<ul class="navs">
<li>
<router-link to="/regist">注册</router-link>
</li>
<li>
<router-link to="/login">登录</router-link>
</li>
<li>
<router-link to="/CooperUser">合作平台</router-link>
</li>
</ul>
</div>
</div>
</header>
</template>
方法二:
实现思路很简单:就是利用路由的导购守卫beforeEach在每次页面跳转前更改对应的title
第一步:首先在route里面给每个路由加上meta属性
{
path: '/login',
name: 'login',
component(resolve) {
require(['./views/login.vue'], resolve)
},
meta: {
title: '登录页',
keepAlive: true, // 需要被缓存
}
},
{
path: '/regist',
name: 'regist',
component(resolve) {
require(['./views/regist.vue'], resolve)
},
meta: {
title: '注册页',
keepAlive: true, // 需要被缓存
}
},
{
path: '/newList',
name: 'newlist',
component(resolve) {
require(['./views/newsList.vue'], resolve)
},
meta: {
title: '新闻列表',
keepAlive: true, // 需要被缓存
}
}
第二步:在main.js里面加上导航守卫
router.beforeEach((to, from, next) => {
window.document.title = to.meta.title == undefined?‘默认标题’:to.meta.title
if (to.meta.requireAuth) {
let token = Cookies.get(‘access_token’);
let anonymous = Cookies.get(‘user_name’);
if (token) {
next({
path: '/login',
query: {
redirect: to.fullPath
}
})
}
}
next();
})
方法三:
1.先安装插件,命令行执行cnpm install vue-wechat-title --save即可安装。
2.引用插件,在main.js中,首先import然后再use即可,具体代码如下:
import VueWechatTitle from ‘vue-wechat-title’
Vue.use(VueWechatTitle)
3.在路由的配置文件router.js里面配置我们想要的页面标题,代码示例如下:
routes: [{
path: ‘/’,
name: ‘index’,
component: Index,
meta: {
title: “漫岛-一个有趣的网站”
}
},
{
path: ‘/recruit’,
name: ‘recruit’,
component: Recruit,
meta: {
title: “漫岛-团队伙伴招募”
}
}
]
4.最后一步,在app.vue里面添加指令v-wechat-title即可,示例是从官方npm页面copy的,请注意注释部分不要破坏使用规则。具体如下: