40
33

More than 5 years have passed since last update.

Nuxt.js で title タグや meta タグを設定する

Posted at

Nuxt.js で title タグや meta タグを設定するには2つの方法がある。

  1. nuxt.config.js の head プロパティ
  2. pages 配下のページコンポーネントの head メソッド

1. nuxt.config.js の head プロパティ

サンプル

nuxt.config.js
export default {
  head: {
    title: 'title',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'description' }
    ]
  }
}

出力結果

<head>
  <title data-n-head="true">title</title>
  <meta data-n-head="true" charset="utf-8"/>
  <meta data-n-head="true" name="viewport" content="width=device-width, initial-scale=1"/>
  <meta data-n-head="true" data-hid="description" name="description" content="description"/>
</head>
  • charset や viewport など、アプリケーション全体で共通のものを設定するとよい
  • title タグや description も念の為設定しておくとよい(ページコンポーネントで設定し忘れた場合、デフォルト値として働くため)

2. pages 配下のページコンポーネントの head メソッド

サンプル

pages/index.vue
<template>
  <h1>{{ title }}</h1>
</template>

<script>
export default {
  data () {
    return {
      title: 'Hello, World!'
    }
  },
  head () {
    return {
      title: this.title,
      meta: [
        { hid: 'description', name: 'description', content: 'description' }
      ]
    }
  }
}
</script>

出力結果

<head>
  <title data-n-head="true">Hello, world!</title>
  <meta data-n-head="true" data-hid="description" name="description" content="description"/>
</head>
...
  • サンプルのようにコンポーネントのデータを使うことができる
  • title や description など、ページ固有のものを設定する(SEO対策)
40
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
33