vue 动态给每个页面添加title、关键词和描述的方法

Nora ·
更新时间:2024-09-20
· 983 次阅读

前言:直接写html加title和关键词想必大家都知道怎么去加,但用vue框架开发的项目我们怎么去动态的给每个页面添加呢 ↓

先在router.js里面配置我们的title、关键词和描述

{ path: '/train', name: 'Train', component: () => import('../components/page/Train.vue'), meta: { title: '教师培训-恩启官网', content: { keywords: '教师培训、恩启培训、恩启云课堂、特教老师、线上服务、徐紫薇、王学钢', description: '恩启教师培训专注于自闭症行业教师专业技能提升培训,评估师培训。为自闭症康复教师提供科学、系统的在线课程、咨询服务。' } } },

 在main.js里用beforeEach(前置守卫)判断

router.beforeEach((to, from, next) => { if (to.meta.content) { let head = document.getElementsByTagName('head'); let meta = document.createElement('meta'); document.querySelector('meta[name="keywords"]').setAttribute('content', to.meta.content.keywords) document.querySelector('meta[name="description"]').setAttribute('content', to.meta.content.description) meta.content = to.meta.content; head[0].appendChild(meta) } if (to.meta.title) { document.title = to.meta.title; } next() });

这样就行了。

后续补充:vue的特点呢就是组件系统跟数据驱动,嗯,是特别方便的,比如我们一个组件里根据路由状态值判断初始化加载不同的页面(比如在前一个页面有三个按钮:北京、上海、深圳)点击进去不同的城市页面,但我们的页面都是用的同一个组件,如下路由配置:↓

{ path: '/cityDetail', name: 'CityDetail', component: () => import('../components/page/CityDetail.vue'), meta: { title: '', content: { keywords: '', description: '' } } },

这里我们再router.js里没进行关键词的填写,因为他有好几个不同城市加载,我们可以在对应的组件里加个判断

if(orgUrl == 'beijing'){ document.querySelector('meta[name="keywords"]').setAttribute('content', '北京教研中心,恩启教研中心,IEDA教研中心') document.querySelector('meta[name="description"]').setAttribute('content', '恩启诞生于2014年 ,是一家专业的自闭症康复机构。北京教研中心,位于北京市朝阳区孙河地铁站对面弘园五号创意生活园A5,联系方式13021253543,北京教研中心。') document.title = '恩启IDEA·北京教研中心-直营连锁-恩启官网'; }else if(orgUrl == 'shanghai'){ document.querySelector('meta[name="keywords"]').setAttribute('content','上海静安教研中心,恩启教研中心,IEDA教研中心'); document.querySelector('meta[name="description"]').setAttribute('content', '恩启IDEA静安中心坐落于上海市大宁中心广场,毗邻大宁音乐中心,交通便利,生活便捷。'); document.title='恩启IDEA·上海静安教研中心-直营连锁-恩启官网'; }

这样设置就ok了;

总结

到此这篇关于vue 动态给每个页面添加title、关键词和描述的方法的文章就介绍到这了,更多相关vue 添加title、关键词和描述内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



VUE 方法 关键 title 动态

需要 登录 后方可回复, 如果你还没有账号请 注册新账号