vue 動態給每個頁面新增title、關鍵詞和描述的方法
阿新 • • 發佈:2020-08-30
前言:直接寫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、關鍵詞和描述內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!