Vue 單頁應用 動態修改頁面 title
阿新 • • 發佈:2019-01-28
使用 Vue + VueRouter 開發單頁應用時,有些需要修改頁面 title 的場景,可以通過在 router 中新增 meta 元資訊來實現:
routes: [{
name: 'home',
path: '/home/:openname',
component: Home,
meta: {
title: '首頁'
}
}]
新增完 meta 資訊後,還需要在路由跳轉後的回撥中獲取當前頁的 title,並賦值給 document.title:
router.afterEach((to, from, next) => { /* 路由發生變化修改頁面 title */ if (to.meta.title) { document.title = to.meta.title; } next(); })
上述做法在某些 IOS 的瀏覽器或 web-view 中無法生效,所以需要想辦法解決 IOS 下的相容問題,可以利用 iframe 節點的插入和刪除實現相容,具體做法如下:
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 = '/path/fixIosTitle.html?r=' + Math.random(); document.body.appendChild(hackIframe); setTimeout(() => { document.body.removeChild(hackIframe) }, 300) } } });
其中“fixIosTitle.html”是一個空的.html檔案,僅用作一個新的 iframe,供插入、刪除使用。
如此一來,在 IOS 裝置下也能動態改變頁面 title 了,是不是很好的體驗呢~