vue修改浏览器的标题title

方法一: 第一步:在main.js里面添加一个全局指令 Vue.directive('title', { inserted: function (el, binding) { document.title = el.dataset.title } }) 第二步:在要调用的组件里...

方法一:

第一步:在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>


作者:刘其瑞
链接:https://www.jianshu.com/p/406fa692edc8
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章