單頁應用在iOS微信瀏覽器中如何優雅的設置title

最近用Vue2.0 SPA作了個微信應用,遇到了一個比較尷尬的問題。用document.title設置title,在返回時不會再從新設置title。瀏覽器

因爲iOS的微信瀏覽器使用原生的title,在路由返回後不能及時捕獲document.title的修改。微信

有一種hack的解決方案:在document裏append一個空的iframe作僞請求,在修改完標題後進行remove。上代碼。app

封裝設置title的方法ui

const titleUtil = {};

titleUtil.setTitle = (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 = () => {
            setTimeout(() => {
                i.remove();
            }, 9);
        };
        document.body.appendChild(i);
    }
};

export default titleUtil;

動態引入組件並設置meta,統一管理code

{ 
  path: '/city_select', name: 'city.select', component:  (resolve) => {
    require(['../components/page/fund/city.select'], resolve);
  } , meta: { title: '切換城市' } 
}

在路由鉤子afterEach中設置titlecomponent

router.afterEach((route) => {
  titleUtil.setTitle(route.matched[0].meta.title || '首頁');
});

搞定收工。router

若是有更好的方式但願各位不吝賜教。ip

相關文章
相關標籤/搜索