在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)


基础教程推荐
猜你喜欢
- 纯CSS实现一个简单步骤条的示例代码 2024-02-04
- JS代码放在head和body中的区别分析 2024-01-06
- 详解CSS中postion和opacity及cursor的特性 2023-12-30
- 图文解析AJAX的原理 2023-01-20
- jQuery实现的浮动层div浏览器居中显示效果 2024-01-23
- Ajax 的初步实现(使用vscode+node.js+express框架) 2023-02-23
- SpringBoot集成WebSocket,前端使用Vue 2023-10-08
- Ajax返回数据之前的loading等待效果 2023-02-14
- 前端小白的学习之路html与css的较量【一】 2023-10-27
- Ajax犯的错误处理方法 2023-01-21