前言:直接寫html加title和關鍵詞想必大家都知道怎么去加,但用vue框架開發的項目我們怎么去動態的給每個頁面添加呢 ↓
先在router.js里面配置我們的title、關鍵詞和描述
1
2
3
4
5
6
7
8
9
10
11
12
|
{ path: '/train' , name: 'Train' , component: () => import( '../components/page/Train.vue' ), meta: { title: '教師培訓-恩啟官網' , content: { keywords: '教師培訓、恩啟培訓、恩啟云課堂、特教老師、線上服務、徐紫薇、王學鋼' , description: '恩啟教師培訓專注于自閉癥行業教師專業技能提升培訓,評估師培訓。為自閉癥康復教師提供科學、系統的在線課程、咨詢服務。' } } }, |
在main.js里用beforeEach(前置守衛)判斷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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的特點呢就是組件系統跟數據驅動,嗯,是特別方便的,比如我們一個組件里根據路由狀態值判斷初始化加載不同的頁面(比如在前一個頁面有三個按鈕:北京、上海、深圳)點擊進去不同的城市頁面,但我們的頁面都是用的同一個組件,如下路由配置:↓
1
2
3
4
5
6
7
8
9
10
11
12
|
{ path: '/cityDetail' , name: 'CityDetail' , component: () => import( '../components/page/CityDetail.vue' ), meta: { title: '' , content: { keywords: '' , description: '' } } }, |
這里我們再router.js里沒進行關鍵詞的填寫,因為他有好幾個不同城市加載,我們可以在對應的組件里加個判斷
1
2
3
4
5
6
7
8
9
|
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、關鍵詞和描述內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/LingHuzh/article/details/107709709