LoginSignup
2
0

More than 1 year has passed since last update.

【Nuxt.js】titleなどHTMLのheadの内容をページごとに設定してみる

Last updated at Posted at 2022-05-29

この記事について

Nuxt.jsでページtitleやmetaタグなどをページごとに設定してみましたので、実装方法を記録として残したいと思います。

対象読者

  • Nuxt.jsで画面開発を行っている方
  • ページtitleやog:imageなどmetaタグに関する情報を動的に変更したい方

環境

内容 バージョン
node 16.14.2
yarn 1.22.15
nuxt 2.15.8

実装してみる

nuxt.config.js の記述

nuxt.config.js で全ページ共通のheadタグの内容を記述できます。

以下の例では、全ページのtitleが タイトルテスト となり、指定したmeta情報も設定されます。

nuxt.config.js
export default {
  head: {
    title: 'タイトルテスト',
    htmlAttrs: { lang: 'ja' },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
  },
};

以下のように titleTemplate を使用してページごとに head の内容を定義すると、ページごとにタイトルの内容を変更することが可能です。

nuxt.config.js
export default {
  head: {
    titleTemplate: 'タイトルテスト - %s ページ',
    htmlAttrs: { lang: 'ja' },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
  },
};

各ページでのタイトル設定

個別ページ側では head メソッドを使用します。
以下の例では、titleには タイトルテスト - ホーム ページ が表示されます。
nuxt.config.js で設定した titleTemplate%s の部分が個別ページ側の title の値に置き換えられます。

pages/index.vue
<template>
  <div>ホームページ</div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  head() {
    return {
      title: 'ホーム',
    };
  },
});
</script>

title以外にもmetaタグも個別ページ側で記載することが可能であるため、ページごとにOpen Graphの内容を設定することができます。

nuxt.config.js
export default {
  head: {
    titleTemplate: 'タイトルテスト - %s ページ',
    htmlAttrs: {
      lang: 'ja',
      // metaでogを使用するため
      prefix: 'og: http://ogp.me/ns#',
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
  },
};
pages/index.vue
<template>
  <div>ホームページ</div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  head() {
    return {
      title: 'ホーム',
      meta: [
        {
          hid: 'og:title',
          property: 'og:title',
          content: 'ホームページのog:titleテスト',
        },
        {
          hid: 'og:description',
          property: 'og:description',
          content: 'ホームページのog:og:descriptionテスト',
        },
        {
          hid: 'og:image',
          property: 'og:image',
          content:
            'http://illustrain.com/img/work/2016/illustrain04-kaisya01.png',
        },
      ],
    };
  },
});
</script>

参考

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

2
0
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
2
0