原文链接:https://blog.csdn.net/qq_41810005/article/details/90699102(侵删)
方法一:
第一步:在main.js里面添加一个全局指令
Vue.directive('title', {
inserted: function (el, binding) {
document.title = el.dataset.title
}
})
第二步:在要调用的组件里面,随便找一个div加入如下代码
v-title data-title="首页"
案例:
<template>
<div v-title data-title="首页"></div>
<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>
</template>
方法二:
实现思路很简单:就是利用路由的导购守卫beforeEach在每次页面跳转前更改对应的title
第一步:首先在route里面给每个路由加上meta属性
{ path: '/login', meta: { title: '登录页'},component: ()=> import('@/components/login')},
{ path: '/home', meta: { title: '主页'},component: ()=> import('@/components/home')},
第二步:在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的,请注意注释部分不要破坏使用规则。具体如下:
<!-- 任意元素中加 v-wechat-title 指令 建议将标题放在 route 对应meta对象的定义中 -->
<div v-wechat-title="$route.meta.title"></div>
<!--或者-->
<router-view v-wechat-title="$route.meta.title"></router-view>
网友评论