LoginSignup
4

More than 3 years have passed since last update.

【Vue.js】vue-headの導入について

Posted at

フロント開発をする中、head要素をvueで管理する方法として、
vue-headというライブラリを導入する機会があったので、備忘録としてまとめておく。

前提

vue-routerを導入している事。
※この記事ではvue-routerについての解説は行いません。

手順

導入自体はとても簡単。
まずはnpmコマンドでパッケージをインストール。

npm install vue-head --save

今回はmain.jsで読み込みます。

main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueHead from 'vue-head'

Vue.use(VueHead)
Vue.use(VueRouter)

あとは各ページのコンポーネント毎にタイトルとmetaタグ設定すればOK。

home.vue

export default {
  head: {
    title() {
      return {
        inner: 'App',
        separator: '|',
        complement: 'page',
      }
    },
    meta: [
      { name: 'description', content: 'My description', id: 'desc' }
    ]
  }
    ...
  }
}

router.jsで表示するページ毎のタイトルを定義しておいて、
複数ページで共有するコンポーネントがあれば、簡単にタイトルやmetaの切り替えが出来ます。

更に共通の内容があれば、Mixinする事でよりシンプルに書く事が出来ます。

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
4