Vue标题动态改变

350 阅读1分钟

在Vue开发中路由跳页后想让网页标题跟随网路由页面改变我们可以使用vue-wechat-title

安装

npm install vue-wechat-title --save

使用

在main.js中引入

import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)

在router>index.js中添加meta对象配置title

    const router = new Router({
     
      routes: [
        ...
        {
          path: "/gameDesc", 
          name: 'gameDesc',
          component: resolve => import('@/pages/Game/gameDesc'),
          meta:{
            title: '游戏说明'
          }
        },
        {
          path: "/integralList", 
          name: 'integralList',
          component: resolve => import('@/pages/Game/integralList'),
          meta:{
            title: '积分收取记录'
          }
        }
        ...
     
     ]
    });
     
    router.afterEach(route => {
      // 从路由的元信息中获取 title 属性
      if (route.meta.title) {
        document.title = route.meta.title;
        // 如果是 iOS 设备,则使用如下 hack 的写法实现页面标题的更新
        if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
          const hackIframe = document.createElement('iframe');
          hackIframe.style.display = 'none';
          hackIframe.src = '/static/html/fixIosTitle.html?r=' + Math.random();
          document.body.appendChild(hackIframe);
          setTimeout(_ => {
            document.body.removeChild(hackIframe)
          }, 300)
        }
      }
    });

在App.vue中修改router-view

<router-view v-wechat-title='$route.meta.title'></router-view>

本文章仅以自己防止忘记而记录,不管是我还是其他人,当你看到这篇文章的时候说明你还在从事前端工作,或者在学习前端,所以不管以后遇到什么问题,和挫折,都不要忘记你敲代码的初衷