最近基于VUE做個(gè)SPA手機(jī)端web發(fā)現(xiàn)動(dòng)態(tài)修改頁面標(biāo)題通過document.title=xxxx 來修改著實(shí)蛋疼,而且在IOS的微信端據(jù)說沒效果。百度發(fā)現(xiàn)要針對IOS的微信做點(diǎn)額外的操作,即:創(chuàng)建一個(gè)隱藏的Iframe,然后隨便加載一個(gè)圖片文件,然后加載完成移除,這樣就能修改頁面title了。網(wǎng)上有幾種方案:
1,App.Vue里面設(shè)置title屬性,然后頁面title去綁定,所有子組件修改標(biāo)題就通過 this.$root.data.title=xxxxx;去修改
缺點(diǎn):App.Vue默認(rèn)的el只是body的一個(gè)DIV,這樣干需要綁定整個(gè)html
2,通過自定義指令實(shí)現(xiàn)
Vue.directive('title', { inserted: function (el, binding) { document.title = el.innerText el.remove() }})調(diào)用方法: <div v-title>標(biāo)題內(nèi)容</div>
優(yōu)點(diǎn):這樣自定義程度較大(暫且不討論IOS微信端是否能修改成功)
缺點(diǎn):無法滿足某些JS方法中修改頁面標(biāo)題的需求,例如頁面為一個(gè)websocket的頁面,收到消息要?jiǎng)討B(tài)顯示頁面標(biāo)題這時(shí)候頻繁去修改div綁定的text并不恰當(dāng)
針對網(wǎng)上查到的上面兩種方法,我進(jìn)行了合并,利用vue的插件實(shí)現(xiàn)SPA的頁面標(biāo)題修改:
var plugin={};plugin.install=function(Vue,options){ Vue.prototype.$title=function(title){ document.title=title; var iframe=document.createElement("iframe"); iframe.style.display='none'; iframe.setAttribute('src','/e.png'); var loadedCallback=()=>{ iframe.removeEventListener('load',loadedCallback); document.body.removeChild(iframe); }; iframe.addEventListener('load',loadedCallback); document.body.appendChild(iframe); };};module.exports=plugin;調(diào)用方法: this.$title('xxxxxx'); 當(dāng)然你可以替換為一個(gè)綁定的變量,然后watch進(jìn)行實(shí)時(shí)調(diào)整。
ps:Vue Spa切換頁面時(shí)更改標(biāo)題
在Vue組件化開發(fā)過程中,因?yàn)槭菃雾撁骈_發(fā),但是有時(shí)候需要頁面的title根據(jù)情況改變,于是上網(wǎng)查了一下,各種說法花(wo)里(kan)胡(bu)哨(dong), 于是想到一個(gè)黑科技 documet.title="xxx";
隨便創(chuàng)建一個(gè)項(xiàng)目,在獨(dú)立的模塊中,created在鉤子函數(shù)啟動(dòng)之后document.title='標(biāo)題'; 但是據(jù)說在IOS的微信下是無效的,雖然用蘋果機(jī)測試過有用,但是想到這樣會(huì)影響我的代碼潔癖。
<script>export default { data(){ return{ } }, created(){ document.title="首頁" },}</script>于是在github上找到一個(gè)好用的東西 vue-wechat-title
通過 npm install vue-wechat-title 安裝
引入需要的vue-router與頁面需要的組件之后
const router = new VueRouter({ mode: 'history', routes:[ { name: 'index', path: '/', meta: { title: '首頁' }, component: index }, { name: 'root', path: '/root', meta: { title: '肉特' }, component: root } ]});Vue.use(require('vue-wechat-title')); //實(shí)例化參數(shù)在組件中頂部添加一段 <div v-wechat-title="$route.meta.title"></div>
即可實(shí)現(xiàn)改變title效果。
新聞熱點(diǎn)
疑難解答