在Vue中动态地添加meta
标签的keywords
属性和description
属性可以通过修改页面的头部信息来实现。下面小编给大家简单介绍一下具体操作代码!
vue全局动态添加meta属性代码
//打开main.js,在router.beforeEach里新增以下代码
router.beforeEach((to,from,next)=>{
if(Object.keys(to.meta).length>0 && to.matched.length>0){
let this_meta=to.matched[to.matched.length-1].meta
//动态添加标题
if(this_meta.title)document.title=this_meta.title
let head = document.getElementsByTagName('head');
//动态添加keywords
let keyword = document.createElement('meta');
if(document.querySelector('meta[name="keywords"]')){
document.querySelector('meta[name="keywords"]').setAttribute('content',this_meta.keywords)
}else{
keyword.setAttribute('name','keywords')
keyword.setAttribute('content',this_meta.keywords)
head[0].appendChild(keyword)
}
//动态添加description
let description = document.createElement('meta');
if(document.querySelector('meta[name="description"]')){
document.querySelector('meta[name="description"]').setAttribute('content',this_meta.description)
}else{
description.setAttribute('name','description')
description.setAttribute('content',this_meta.description)
head[0].appendChild(description)
}
}
next()
})
以上是编程学习网小编为您介绍的“vue全局动态添加meta属性(title,keywords,description)”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。
沃梦达教程
本文标题为:vue全局动态添加meta属性(title,keywords,description)


猜你喜欢
- Ajax提交表单页面刷新很快的解决方法 2023-01-26
- 详解vue 单页应用(spa)前端路由实现原理 2024-02-12
- DIV+CSS 清除浮动常用方法总结 2024-02-07
- 微信小程序开发探究 2023-12-01
- dnf大转移远古3套装掉落规则详解_dnf大转移远古3套装掉落具体位置 2024-02-04
- 基于slideout.js实现移动端侧边栏滑动特效 2024-02-22
- 如何用VUE和Canvas实现雷霆战机打字类小游戏 2024-02-05
- JavaScript生成带有缩进的表格代码 2023-12-02
- 如何制作浮动广告 JavaScript制作浮动广告代码 2024-02-05
- 利用js+css+html实现固定table的列头不动 2024-02-21