美文网首页nuxtjs
nuxt动态设置关键词,描述,标题

nuxt动态设置关键词,描述,标题

作者: 明眸yh | 来源:发表于2020-12-08 14:58 被阅读0次

页面的meta设置对于SEO的设置非常重要,比如你现在要作个新闻页面,那为了搜索引擎对新闻的收录,需要每个页面对新闻都有不同的title和meta设置。

首先了解nuxt下设置meta的方法

  • 借助 head 属性,Nuxt.js 可以在 nuxt.config.js 中配置应用的 meta 信息。
module.exports = {
  /*
  ** Headers of the page
  */
  head: {
    title: '前端小喵', // 网站标题
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '此处是网站描述' },
      { hid: 'keywords', name: 'keywords', content: '此处是网站关键词' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  }
}
  • 组件中Nuxt.js 使用了 vue-meta 更新应用的 头部标签(Head)html 属性
head(){
  return{
    title: `前端小喵`,
    meta:[
      {hid:'description',name:'description',content: '前端小喵'},
      {hid:'keywords',name:'keywords',content: '前端小喵'}
    ]
  }
}

动态设置meta信息

下面以一个新闻详情的meta信息设置为例:
首先从列表传参到详情页面获取meta信息,然后再通过this绑定到页面上。
/new页面,传id参数到new-id页面
来点假数据吧

list: [
  {
    id: '1',
    title: '前端小喵'
  },
  {
    id: '2',
    title: '前端小喵'
  }
]
<li v-for="(item, index) in list" :key="'list_'+item.id">
  <nuxt-link :to="`/new/${item.id}`" :title="item.title">
    {{item.title}}
  </nuxt-link>
</li>
...

详情页面接收参数,从后台接口获取关键词,描述,标题
来点假数据吧

{
  "code":0,
  "message":"success",
  "data":{
    "id":1,
    "title":"前端小喵",
    "keywords": "前端小喵",
    "description": "前端小喵"
  }
}
async asyncData({ store, params, error, req, query }) {
  try {
    const isServer = process.server
    const token = isServer ? req.cookies[TokenKey] : getToken()
    let { id } = params
    let par = {
      id: id
    }
    let [detialRes,] = await Promise.all([
      user_api_send('/api/***********', par, 'post', token),
    ])
    return {
      detial: detialRes.data
    }
  } catch(err) {
    console.log(err)
  }
},
data() {
  return {
    detial: {
      
    }
  }
}

设置head

head(){
  return{
    title: `前端小喵-${this.detial.title}`,
    meta:[
      {hid:'description',name:'description',content: this.detial.description || '前端小喵'},
      {hid:'keywords',name:'keywords',content: this.detial.keywords || '前端小喵'}
    ]
  }
}

这样就设置完成了。

相关文章

网友评论

    本文标题:nuxt动态设置关键词,描述,标题

    本文链接:https://www.haomeiwen.com/subject/onuuwktx.html