1. 程式人生 > 程式設計 >nuxt 伺服器渲染動態設定 title和seo關鍵字的操作

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()
});

nuxt 伺服器渲染動態設定 title和seo關鍵字的操作

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

以上這篇nuxt 伺服器渲染動態設定 title和seo關鍵字的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。