Vue设置页面的title

原文地址:http://www.cnblogs.com/JimmyBright/p/7410771.html

前端框架如Vue、React等都是单页面的应用,也就是说整个web站点其实都是一个index页面,所谓的页面跳转都是替换index.html里边的内容,而页面的title是在每个页面初始化的时候才设置一次。对于现在的前端框架,传统的每个页面设置title标签的做法是不行的。

下面是在Vue框架下,利用路由来设置title的思路,当然还有别的方法。

先看项目目录

Vue设置页面的title

router的index.js代码如下:

 import Vue          from 'vue'
import Router from 'vue-router'
import signProtocol from '@/components/pages/signProtocol'
import personInfo from '@/components/pages/personInfo'
import uploadPhoto from '@/components/pages/uploadPhoto'
import utils from '@/lib/utils'
Vue.use(Router)
var router= new Router({
mode:'history',
routes: [
{
path: '/',
name: 'uploadPhoto',
title:'上传身份证',
component: uploadPhoto,
},
{
path:'/personinfo',
name:'personInfo',
title:'提交信息',
component:personInfo
},
{
path:'/signprotocol',
name:'signProtocol',
title:'签署协议',
component:signProtocol
}
]
})
router.beforeEach((to, from, next) => {
next()
});
router.afterEach((transition)=>{
let name = transition.name
let item = router.options.routes.filter((ele)=>{return ele.name == name})
console.log(item[0].title)
utils.setTitle(item[0].title)
})
export default router;

router/index.js

代码中在router中增加了参数title,在路由结束钩子afterEach里取到对应页面的title,再设置上去就可以了

需要用到的utils里的方法如下:

 import axios from 'axios';
const SCREEN_WIDTH = document.body.clientWidth
const SCREEN_HEIGHT=document.body.scrollHeight
function service_sidi(url,body,successCallback,errorCallBack){
axios.post(process.env.Host_url+url,body).then(function(result){
successCallback(result)
},function(error){errorCallBack(error)})
}
function service_jz(url,body,successCallback,errorCallBack){
axios.post(process.env.Host_url+url,body).then(function(result){
successCallback(result)
},function(error){errorCallBack(error)})
}
function setTitle(title) {
document.title = title
var mobile = navigator.userAgent.toLowerCase()
if (/iphone|ipad|ipod/.test(mobile)) {
var iframe = document.createElement('iframe')
iframe.style.display = 'none'
// iframe.setAttribute('src', '')
var iframeCallback = function () {
setTimeout(function () {
iframe.removeEventListener('load', iframeCallback)
document.body.removeChild(iframe)
}, 0)
}
iframe.addEventListener('load', iframeCallback)
document.body.appendChild(iframe)
}
}
var obj={
service_sidi:service_sidi,
service_jz:service_jz,
SCREEN_WIDTH:SCREEN_WIDTH,
SCREEN_HEIGHT:SCREEN_HEIGHT,
setTitle:setTitle
}
export default obj;

lib/utils/index.js

上一篇:【BZOJ4144】[AMPPZ2014]Petrol(最短路+最小生成树+并查集)


下一篇:Poj(3686),最小权匹配,多重匹配,KM