nuxt 服務(wù)器渲染動態(tài)設(shè)置 title和seo關(guān)鍵字的操作
使用如下鉤子即可,但是前提條件是 沒有默認配置head的title
asyncData ({ app }, callback) {
app.head.title = ‘new title'
callback(null, {})
},
補充知識:vue 每個頁面動態(tài)切換title keywords description (seo的設(shè)置)
最近接觸到需要使用到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內(nèi)容',
content:{
keywords:'這里是第一個keywords',
description:'這里是第一個description',
},
}
},
{
path: '/trueBag',
name: 'trueBag',
component: trueBag,
meta: {
title: 'trueBag頁面的title內(nèi)容',
content:{
keywords:'這里是第二個keywords',
description:'這里是第二個description',
},
}
},
]
第二步 在main.js里面設(shè)置,路由發(fā)生變化修改頁面meta
前提是已經(jīng)導(dǎo)入了router
// 現(xiàn)在可以直接復(fù)制,不需要改什么東西
// 當然如果你想添加的meta,不僅僅只有keywords 和 description的時候,
// 自己可以舉一反三 :
// setAttribute 后面就是設(shè)置它的值前提是要和router里面的content是相對應(yīng)的
//要不然是獲取不到的
//document.querySelector(‘meta[name=“description”]').setAttribute(‘content', to.meta.content.description)
router.beforeEach((to, from, next) => {
/* 路由發(fā)生變化修改頁面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)
}
// /* 路由發(fā)生變化修改頁面title */
if (to.meta.title) {
document.title = to.meta.title;
}
next()
});

具體是否成功可以f12查看,如果沒有出來,一步一步打印一下,看自己是哪里出錯。
以上這篇nuxt 服務(wù)器渲染動態(tài)設(shè)置 title和seo關(guān)鍵字的操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue2+elementUI實現(xiàn)下拉樹形多選框效果實例
這篇文章主要給大家介紹了關(guān)于vue2+elementUI實現(xiàn)下拉樹形多選框效果的相關(guān)資料,這是最近的工作中遇到的一個需求,對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
VueJS 集成 Medium Editor的示例代碼 (自定義編輯器按鈕)
本篇文章主要介紹了VueJS 集成 Medium Editor的示例代碼 (自定義編輯器按鈕),具有一定的參考價值,有興趣的可以了解一下2017-08-08
關(guān)于vue-treeselect綁值、回顯等常見問題的總結(jié)
這篇文章主要介紹了關(guān)于vue-treeselect綁值、回顯等常見問題的總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù))
這篇文章主要介紹了vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

