原文地址:http://www.cnblogs.com/JimmyBright/p/7410771.html
前端框架如Vue、React等都是單頁面的應用,也就是說整個web站點其實都是一個index頁面,所謂的頁面跳轉都是替換index.html裡邊的內容,而頁面的title是在每個頁面初始化的時候才設定一次。對於現在的前端框架,傳統的每個頁面設定title標籤的做法是不行的。
下面是在Vue框架下,利用路由來設定title的思路,當然還有別的方法。
先看專案目錄
router的index.js程式碼如下:
1 import Vue from 'vue' 2 import Router from 'vue-router' 3 import signProtocol from '@/components/pages/signProtocol' 4 import personInfo from '@/components/pages/personInfo' 5 import uploadPhoto from '@/components/pages/uploadPhoto' 6 import utils from '@/lib/utils' 7 Vue.use(Router) 8 var router= new Router({ 9 mode:'history', 10 routes: [ 11 { 12 path: '/', 13 name: 'uploadPhoto', 14 title:'上傳身份證', 15 component: uploadPhoto, 16 }, 17 { 18 path:'/personinfo', 19 name:'personInfo', 20 title:'提交資訊', 21 component:personInfo 22 }, 23 { 24 path:'/signprotocol', 25 name:'signProtocol', 26 title:'簽署協議', 27 component:signProtocol 28 } 29 ] 30 }) 31 router.beforeEach((to, from, next) => { 32 next() 33 }); 34 router.afterEach((transition)=>{ 35 let name = transition.name 36 let item = router.options.routes.filter((ele)=>{return ele.name == name}) 37 console.log(item[0].title) 38 utils.setTitle(item[0].title) 39 }) 40 export default router;
程式碼中在router中增加了引數title,在路由結束鉤子afterEach裡取到對應頁面的title,再設定上去就可以了
需要用到的utils裡的方法如下:
1 import axios from 'axios'; 2 const SCREEN_WIDTH = document.body.clientWidth 3 const SCREEN_HEIGHT=document.body.scrollHeight 4 function service_sidi(url,body,successCallback,errorCallBack){ 5 axios.post(process.env.Host_url+url,body).then(function(result){ 6 successCallback(result) 7 },function(error){errorCallBack(error)}) 8 } 9 function service_jz(url,body,successCallback,errorCallBack){ 10 axios.post(process.env.Host_url+url,body).then(function(result){ 11 successCallback(result) 12 },function(error){errorCallBack(error)}) 13 } 14 function setTitle(title) { 15 document.title = title 16 var mobile = navigator.userAgent.toLowerCase() 17 if (/iphone|ipad|ipod/.test(mobile)) { 18 var iframe = document.createElement('iframe') 19 iframe.style.display = 'none' 20 // iframe.setAttribute('src', '') 21 var iframeCallback = function () { 22 setTimeout(function () { 23 iframe.removeEventListener('load', iframeCallback) 24 document.body.removeChild(iframe) 25 }, 0) 26 } 27 iframe.addEventListener('load', iframeCallback) 28 document.body.appendChild(iframe) 29 } 30 } 31 var obj={ 32 service_sidi:service_sidi, 33 service_jz:service_jz, 34 SCREEN_WIDTH:SCREEN_WIDTH, 35 SCREEN_HEIGHT:SCREEN_HEIGHT, 36 setTitle:setTitle 37 } 38 export default obj;