vue 2.0 单页面应用动态修改微信中的title

下面是utils.js文件中的内容:


// 第一种修改title的方法 :
const setWechatTitle = function(title) {
    document.title = title;
    let mobile = navigator.userAgent.toLowerCase();
    if (/iphone|ipad|ipod/.test(mobile)) {
        let iframe = document.createElement('iframe');
        iframe.style.visibility = 'hidden';
        // 替换成站标favicon路径或者任意存在的较小的图片即可
        iframe.setAttribute('src', '//m.baidu.com/favicon.ico');
        let iframeCallback = function() {
            setTimeout(function() {
                iframe.removeEventListener('load', iframeCallback)
                document.body.removeChild(iframe)
            }, 10)
        };
        iframe.addEventListener('load', iframeCallback)
        document.body.appendChild(iframe)
    }
};

// 第二种修改title的方法,其中包含iframe的设置:
let setTitleHack = function (t) {
    document.title = t;
    let iframe = document.createElement('iframe');
    iframe.style.visibility = 'hidden';
    iframe.style.width = '1px';
    iframe.style.height = '1px';
    iframe.src = '//m.baidu.com/favicon.ico';
    iframe.onload = function () {
        setTimeout(function () {
            iframe.remove();
        }, 10);
    };
    document.body.appendChild(iframe);
};

// 在文件的最下方输出这两个方法:
module.exports = {
    setWechatTitle,
    setTitleHack
};

};
准备好上面的代码,接下来就看你需要在哪里使用了,如果是单页面应用的话,我们一般是在router.js文件中使用,因为路由导航发生时会执行钩子,我们可以使用 router.beforeEach 注册一个全局的 before 钩子,然后在router.beforeEach((to, from, next) => {...})修改title。
使用方式如下:

import { setTitleHack } from './utils';

vue 2.0定义路由的时候,可以将所有的路由都放在一个组件配置对象中,同时,可以配置 meta 字段,在其中添加一个title的属性,值就是你这个页面要显示页面上方的title,像下面这样:

const routes = [
    {path: '/auth', component: auth, name: 'auth', meta: {title: '�授权页'}},
    {path: '/home', component: Home, name: 'home', meta: {title: ' 首页' }},
];

二,在beforeEach中直接像下面这样写就可以了。


router.beforeEach((to, from, next) => {
    setTitleHack(to.meta.title);
    next();
});

});
三,还有一种情况就是在单个组件中使用,比如说你当前这个页面的title是根据不同用户的姓名来,而用户的姓名都是通过后台来获取的,是动态的,所以,需要在用户详情的页面中来动态修改title,使用方式其实也差不多,下面就让我们来看一下代码:
同样也是先引用,我这次把两个方法都引用进来,上面我们用的是setTitleHack,下面我们来用一下setWechatTitle:

import { setWechatTitle, setTitleHack } from './../utils';

在我现在这个项目中,取数据的过程是在beforeCreate钩子中做的,项目中获取数据用的是vue-resource,修改title就在取到了数据以后,下面来看代码:

beforeCreate(){
      let group_id = this.$route.params.id;
      let dataUrl = "group/detail?group_id=" + group_id;
      this.$http.get(dataUrl)
            .then(({data:{code, content, jssdk, msg}}) => {
                  if (code === 0) {
                        this.content = content;
                        setWechatTitle(content.header.name + '团');
                        // 取到名称之后直接修改title。
                    } else {
                        MessageBox('提示', msg);
                    }
                }, ({data:{msg}}) => {
                    MessageBox('提示', msg);
                });
        },

出处链接 https://www.jianshu.com/p/ce0e829b1bc2

你可能感兴趣的:(vue 2.0 单页面应用动态修改微信中的title)