vue2动态给微信单页应用更改标题

现在公司项目的重构,用到的是vue2.0,做的是一个微信m站,但是由于是SPA单页应用,所以就没有所谓的页面 都是router的跳转
而网页的标题 随着路由的改变而改变 也就成了一个(伪)需求

问题

在iOS的微信中 一个SPA应用 想要改变微信顶部导航栏的标题 使用document.title = xxx来改变网页标题是无效的
原因大致就是因为在微信中webview只加载网页标题一次 动态改变是无效的 除非都以新页面打开

解决方法

在网上查阅的资料都是说vue1的解决方法,并没有一个vue2的相关解决方法,因为2中的router与1发生变化,那么哪些解决方法也就不适用了,下面是本人使用的vue2的解决办法
代码如下

  • 先创建一个方法 这里我是放在utils文件夹中起名为setWechatTitle.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
    * Created by yccc on 2017/4/30.
    */
    module.exports = function (title) {
    document.title = title;
    let ua = navigator.userAgent;
    if (/\bMicroMessenger\/([\d\.]+)/.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    var i = document.createElement('iframe');
    i.src = '/favicon.ico';
    i.style.display = 'none';
    i.onload = function () {
    setTimeout(function () {
    i.remove();
    }, 9);
    };
    document.body.appendChild(i);
    }
    };
  • main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import setWechatTitle from './utils/setWechatTitle.js' // 导入方法
//.....some code
import router from './router' // 导入的路由
new Vue({ // vue实例
el: '#app',
router,
store,
template: '<App/>',
components: {App}
})
//
router.beforeEach((to, from, next) => {
typeof to.meta.pageTitle !== undefined && setWechatTitle(to.meta.pageTitle)
next() //确保要调用 next 方法,否则钩子就不会被 resolved。
})
  • 至此只需要在route中加入meta属性即可
  • router/ index.js
    1
    2
    3
    4
    5
    6
    7
    { // 我的
    path: '/my',
    component: (reslove) => require(['../views/My/my.vue'], reslove),
    meta: {
    pageTitle: '我的页面'
    }
    }

可以在手机微信上检验效果

文章目录
  1. 1. 问题
  2. 2. 解决方法
|