最近接觸到需要使用到Seo,要求每個頁面擁有不同的title,keywords,description
!!!在這裡先添加一步:
html檔案添加
<meta data-n-head="1" data-hid="description" name="description" content="">
<meta data-n-head="1" data-hid="keywords" name="keywords" content="">
第一步 在router裡面index.js檔案夾中
routes: [
{
path: '/',
name: 'main',
component: Main,
meta: {
title: '首頁title内容',
content:{
keywords:'這裡是第一個keywords',
description:'這裡是第一個description',
},
}
},
{
path: '/trueBag',
name: 'trueBag',
component: trueBag,
meta: {
title: 'trueBag頁面的title内容',
content:{
keywords:'這裡是第二個keywords',
description:'這裡是第二個description',
},
}
},
]
第二步 在main.js裡面設定,路由發生變化修改頁面meta
前提是已經導入了router
// 現在可以直接複制,不需要改什麼東西
// 當然如果你想添加的meta,不僅僅隻有keywords 和 description的時候,
// 自己可以舉一反三 :
// setAttribute 後面就是設定它的值前提是要和router裡面的content是相對應的
//要不然是擷取不到的
//document.querySelector(‘meta[name=“description”]’).setAttribute(‘content’, to.meta.content.description)
router.beforeEach((to, from, next) => {
/* 路由發生變化修改頁面meta */
console.log(to.meta.content)
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)
}
// /* 路由發生變化修改頁面title */
if (to.meta.title) {
document.title = to.meta.title;
}
next()
});

具體是否成功可以f12檢視,如果沒有出來,一步一步列印一下,看自己是哪裡出錯,