前言:直接寫(xiě)html加title和關(guān)鍵詞想必大家都知道怎么去加,但用vue框架開(kāi)發(fā)的項(xiàng)目我們?cè)趺慈?dòng)態(tài)的給每個(gè)頁(yè)面添加呢 ↓
先在router.js里面配置我們的title、關(guān)鍵詞和描述
1
2
3
4
5
6
7
8
9
10
11
12
|
{ path: '/train' , name: 'Train' , component: () => import( '../components/page/Train.vue' ), meta: { title: '教師培訓(xùn)-恩啟官網(wǎng)' , content: { keywords: '教師培訓(xùn)、恩啟培訓(xùn)、恩啟云課堂、特教老師、線上服務(wù)、徐紫薇、王學(xué)鋼' , description: '恩啟教師培訓(xùn)專(zhuān)注于自閉癥行業(yè)教師專(zhuān)業(yè)技能提升培訓(xùn),評(píng)估師培訓(xùn)。為自閉癥康復(fù)教師提供科學(xué)、系統(tǒng)的在線課程、咨詢(xún)服務(wù)。' } } }, |
在main.js里用beforeEach(前置守衛(wèi))判斷
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() }); |
這樣就行了。
后續(xù)補(bǔ)充:vue的特點(diǎn)呢就是組件系統(tǒng)跟數(shù)據(jù)驅(qū)動(dòng),嗯,是特別方便的,比如我們一個(gè)組件里根據(jù)路由狀態(tài)值判斷初始化加載不同的頁(yè)面(比如在前一個(gè)頁(yè)面有三個(gè)按鈕:北京、上海、深圳)點(diǎn)擊進(jìn)去不同的城市頁(yè)面,但我們的頁(yè)面都是用的同一個(gè)組件,如下路由配置:↓
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: '' } } }, |
這里我們?cè)賠outer.js里沒(méi)進(jìn)行關(guān)鍵詞的填寫(xiě),因?yàn)樗泻脦讉€(gè)不同城市加載,我們可以在對(duì)應(yīng)的組件里加個(gè)判斷
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年 ,是一家專(zhuān)業(yè)的自閉癥康復(fù)機(jī)構(gòu)。北京教研中心,位于北京市朝陽(yáng)區(qū)孫河地鐵站對(duì)面弘園五號(hào)創(chuàng)意生活園A5,聯(lián)系方式13021253543,北京教研中心。' ) document.title = '恩啟IDEA·北京教研中心-直營(yíng)連鎖-恩啟官網(wǎng)' ; } else if (orgUrl == 'shanghai' ){ document.querySelector( 'meta[name="keywords"]' ).setAttribute( 'content' , '上海靜安教研中心,恩啟教研中心,IEDA教研中心' ); document.querySelector( 'meta[name="description"]' ).setAttribute( 'content' , '恩啟IDEA靜安中心坐落于上海市大寧中心廣場(chǎng),毗鄰大寧音樂(lè)中心,交通便利,生活便捷。' ); document.title= '恩啟IDEA·上海靜安教研中心-直營(yíng)連鎖-恩啟官網(wǎng)' ; } |
這樣設(shè)置就ok了;
總結(jié)
到此這篇關(guān)于vue 動(dòng)態(tài)給每個(gè)頁(yè)面添加title、關(guān)鍵詞和描述的方法的文章就介紹到這了,更多相關(guān)vue 添加title、關(guān)鍵詞和描述內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/LingHuzh/article/details/107709709