vue 修改标题栏_VUE动态修改titile的三种方法

本文介绍了在Vue项目中动态修改页面标题的三种方法:1) 在main.js中通过beforeEach钩子和路由元信息修改;2) 使用vue-meta插件,支持异步数据请求时的动态更新;3) 引入vue-wechat-title插件,尤其适用于解决iOS设备标题更新问题。详细步骤和代码示例分别进行了说明。
摘要由CSDN通过智能技术生成

第一种:适用于在已经定义好title的情况下,例如首页,关于页等等

1.1 main.js

const defaultTitle = '默认 title'router.beforeEach((to, from, next)=>{

document.title= to.meta.title ?to.meta.title : defaultTitle

next()

})

1.2 index.js

routes: [

{

name:'home',

path:'/home/:openname',

component: Home,

meta: {

title:'首页'}

}

]

第二种:vue-meta 插件(适用于无法固定title的情况下,例如文章页)

2.1 安装

npm install vue-meta --save

2.2 在main.js引入

import Meta from 'vue-meta'Vue.use(Meta)

2.3 为需要修改的页面单独定义metaInfo

export default{

metaInfo: {

title:'This is the test',

meta: [

{ charset:'utf-8'},

{ name:'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes'}

]

}

}

2.4 异步请求数据可以使用

如果component中使用了异步请求数据,可以使用 metaInfo() 方法。

{{{ title }}}

name:'post',

data () {return{

title:''description:'这是一篇文章...'}

},

metaInfo () {return{

title:this.title,

meta: [

{ vmid:'description', name: 'description', content: this.description }

]

}

},

created () {this.initData()

},

methods: {

initData () {

axios.get('some/url').then((resp) =>{//设置title时 metaInfo 会同时更新

this.title =resp.titlethis.description =resp.decription

})

}

}

}

第三种:vue-wechat-title

3.1 安装

npm install vue-wechat-title --save

3.2 在main.js中引入

import VueWechatTitle from 'vue-wechat-title'Vue.use(VueWechatTitle)

3.3 使用

在router>index.js中添加meta对象配置title

const router = new Router({

routes: [

...

{

path: "/gameDesc",

name: 'gameDesc',

component: resolve => import('@/pages/Game/gameDesc'),

meta:{

title: '游戏说明'

}

},

{

path: "/integralList",

name: 'integralList',

component: resolve => import('@/pages/Game/integralList'),

meta:{

title: '积分收取记录'

}

}

...

]

});

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 = '/static/html/fixIosTitle.html?r=' + Math.random();

document.body.appendChild(hackIframe);

setTimeout(_ => {

document.body.removeChild(hackIframe)

}, 300)

}

}

});

export default router;

在App.vue中修改router-view

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值