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

您所在的位置:网站首页 设置网页标题用哪个标志好呢怎么弄 vue 动态给每个页面添加title、关键词和描述

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

2024-07-09 11:18| 来源: 网络整理| 查看: 265

前言:直接写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了;

如有错误请大家评论纠正,谢谢~~~~



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3