最近基于VUE做個SPA手機端web發(fā)現(xiàn)動態(tài)修改頁面標題通過document.title=xxxx
來修改著實蛋疼,而且在IOS的微信端據(jù)說沒效果。百度發(fā)現(xiàn)要針對IOS的微信做點額外的操作,即:創(chuàng)建一個隱藏的Iframe,然后隨便加載一個圖片文件,然后加載完成移除,這樣就能修改頁面title了。網(wǎng)上有幾種方案:
1,App.Vue里面設(shè)置title屬性,然后頁面title去綁定,所有子組件修改標題就通過 this.$root.data.title=xxxxx
;去修改
缺點:App.Vue默認的el只是body的一個DIV,這樣干需要綁定整個html
2,通過自定義指令實現(xiàn)
Vue.directive('title', { inserted: function (el, binding) { document.title = el.innerText el.remove() } })
調(diào)用方法: <div v-title>標題內(nèi)容</div>
優(yōu)點:這樣自定義程度較大(暫且不討論IOS微信端是否能修改成功)
缺點:無法滿足某些JS方法中修改頁面標題的需求,例如頁面為一個websocket的頁面,收到消息要動態(tài)顯示頁面標題這時候頻繁去修改div綁定的text并不恰當
針對網(wǎng)上查到的上面兩種方法,我進行了合并,利用vue的插件實現(xiàn)SPA的頁面標題修改:
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');
當然你可以替換為一個綁定的變量,然后watch進行實時調(diào)整。
ps:Vue Spa切換頁面時更改標題
在Vue組件化開發(fā)過程中,因為是單頁面開發(fā),但是有時候需要頁面的title根據(jù)情況改變,于是上網(wǎng)查了一下,各種說法花(wo)里(kan)胡(bu)哨(dong), 于是想到一個黑科技 documet.title="xxx";
隨便創(chuàng)建一個項目,在獨立的模塊中,created在鉤子函數(shù)啟動之后document.title='標題'; 但是據(jù)說在IOS的微信下是無效的,雖然用蘋果機測試過有用,但是想到這樣會影響我的代碼潔癖。
<script> export default { data(){ return{ } }, created(){ document.title="首頁" }, } </script>
于是在github上找到一個好用的東西 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ù)
在組件中頂部添加一段 <div v-wechat-title="$route.meta.title"></div>
即可實現(xiàn)改變title效果。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com