nuxt 如何實現服務器渲染并動態設置 title和seo關鍵字?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
使用如下鉤子即可,但是前提條件是 沒有默認配置head的title
asyncData ({ app }, callback) {
app.head.title = ‘new title'
callback(null, {})
},補充知識:vue 每個頁面動態切換title keywords description (seo的設置)
最近接觸到需要使用到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查看,如果沒有出來,一步一步打印一下,看自己是哪里出錯。
關于nuxt 如何實現服務器渲染并動態設置 title和seo關鍵字問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。