プラグインディレクトリ
plugins
ディレクトリにはルート Vue.js アプリケーションがインスタンス化する前に実行する Javascript プラグインが含まれています。
これは Vue プラグインを追加し、関数や定数を導入する場所です。Vue.use()
を使用する必要がある時は都度 plugins/
ファイルを作成し、nuxt.config.js
の plugins にそのパスを追加する必要があります。
外部パッケージ
サーバーとクライアント両方に HTTP リクエストを行うためには、アプリケーションで外部パッケージ/モジュール(著名な例は axios です)を使用することをお勧めします。
はじめに、npm か Yarn を介してインストールします。
yarn add @nuxtjs/axios
npm install @nuxtjs/axios
例えば、アプリケーション全体の API 呼び出しから発生する可能性のあるエラーに対応するよう、axios インターセプターを設定できます。この例では、API から 500 ステータスエラーが発生した時、sorry というカスタムエラーページにユーザをリダイレクトします。
export default function ({ $axios, redirect }) {
$axios.onError(error => {
if (error.response.status === 500) {
redirect('/sorry')
}
})
}
最後になりますが、モジュールと新しく作成したプラグインをプロジェクト構成に追加します。
module.exports = {
modules: ['@nuxtjs/axios'],
plugins: ['~/plugins/axios.js']
}
そのあとページコンポーネントで直接使用できます:
<template>
<h1>{{ post.title }}</h1>
</template>
<script>
export default {
async asyncData ({ $axios, params }) {
const post = await $axios.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
return { post }
}
}
</script>
モジュールのインストールなしで axios
を使うための他の方法は、<script>
タグで直接 axios
をインポートすることです。
<script>
import axios from 'axios'
export default {
async asyncData ({ params }) {
const { data: post } = await axios.get(`https://api.nuxtjs.dev/posts/${params.id}`)
return { post }
}
}
</script>
nuxt.config.js
の build
> transpile
オプションにパッケージを追加する必要があります。build: {
// ここでwebpack設定を拡張できます
transpile: ['npm-package-name'],
},
Vue プラグイン
v-tooltip などの Vue プラグインを使用してアプリケーションにツールチップを表示する場合、アプリを起動する前にプラグインを設定する必要があります。
はじめにインストールをする必要があります
yarn add v-tooltip
npm install v-tooltip
次にファイル plugins/vue-tooltip.js
を作成します
import Vue from 'vue'
import VTooltip from 'v-tooltip'
Vue.use(VTooltip)
plugins プロパティ
次に nuxt.config.js
の plugins
キー内にファイルパスを追加します。plugins プロパティを使用すると、簡単に Vue.js プラグインをメインアプリケーションに追加できます。plugins
プロパティで定義されているすべてのパスは、メインアプリケーションを初期化する前にインポートされます。
export default {
plugins: ['~/plugins/vue-tooltip.js']
}
ES6 プラグイン
プラグインが node_modules
にあり、ES6 モジュールをエクスポートする場合、transpile
ビルドオプションに追加する必要がある場合があります:
module.exports = {
build: {
transpile: ['vue-tooltip']
}
}
その他のビルドオプションについては、configuration build のドキュメントを参照してください。
クライアントまたはサーバーサイドのみ
一部のプラグインは SSR がサポートされていないため、ブラウザのみで機能する場合があります。
従来のプラグインに名前を付ける
プラグインがクライアント、もしくはサーバーサイドのみで実行されると想定される場合、.client.js
または .server.js
は、プラグインファイルの拡張子として適用できます。ファイルはそれぞれの(クライアントまたはサーバー)サイドのみに自動的に含まれます。
export default {
plugins: [
'~/plugins/foo.client.js', // クライアントサイドのみ
'~/plugins/bar.server.js', // サーバーサイドのみ
'~/plugins/baz.js' // クライアントサイドとサーバーサイド両方
]
}
オブジェクト構文
plugins
の mode
プロパティ('client'
または 'server'
)でオブジェクト構文を使用することもできます。
export default {
plugins: [
{ src: '~/plugins/both-sides.js' },
{ src: '~/plugins/client-only.js', mode: 'client' }, // クライアントサイドのみ
{ src: '~/plugins/server-only.js', mode: 'server' } // サーバーサイドのみ
]
}
$root
とコンテキストの挿入
ときどき、アプリケーション内で関数や値を利用できるようにしたい場合があります。これらの変数を Vue インスタンス(クライアントサイド)、コンテキスト(サーバーサイド)、さらには Vuex ストアに挿入できます。これらの関数の前に $
を付けるのが慣例です。
Nuxt はこれを簡単に行うための inject(key、value
メソッドを提供します。関数をエクスポートするとき、2 番目のパラメーターとして Inject が指定されます。$
は、キーの先頭に自動的に追加されます。
beforeCreate
フックと created
フックのみがクライアント、サーバーサイド両方から呼び出されることを把握しておくことが重要です。他のすべてのフックはクライアントサイドからのみ呼び出されます。export default ({ app }, inject) => {
// Vue、コンテキスト、そしてストアに $hello(msg)を挿入します。
inject('hello', msg => console.log(`Hello ${msg}!`))
}
export default {
plugins: ['~/plugins/hello.js']
}
$hello
サービスは、ページ、コンポーネント、プラグイン、ストアアクションの context
と this
にアクセスできるようになりました。
export default {
mounted() {
this.$hello('mounted')
// console.log 'Hello mounted!' が呼び出される
},
asyncData({ app, $hello }) {
$hello('asyncData')
// Nuxt <= 2.12 を使用する場合は 👇
app.$hello('asyncData')
}
}
export const state = () => ({
someValue: ''
})
export const actions = {
setSomeValueToWhatever({ commit }) {
this.$hello('store action')
const newValue = 'whatever'
commit('changeSomeValue', newValue)
}
}
Vue.use()
、Vue.component()
を使用しないでください、またグローバルに、Nuxt インジェクション専用のこの関数内に Vue を接続しないでください。サーバーサイドでメモリリークが発生します。extendPlugins プロパティ
プラグインを拡張したり、Nuxt によって作成されたプラグインの順序を変更したりすることができます。この関数は plugin オブジェクトの配列を受け入れ、プラグインオブジェクトの配列を返す必要があります。
プラグインの順序を変更する例:
export default {
extendPlugins(plugins) {
const pluginIndex = plugins.findIndex(
({ src }) => src === '~/plugins/shouldBeFirst.js'
)
const shouldBeFirstPlugin = plugins[pluginIndex]
plugins.splice(pluginIndex, 1)
plugins.unshift(shouldBeFirstPlugin)
return plugins
}
}
グローバルミックスイン
グローバルミックスインは Nuxt プラグインで簡単に追加できますが、正しく処理しないとトラブルやメモリリークが発生する可能性があります。アプリケーションにグローバルミックスインを追加するときは、常にフラグを使用して複数回登録しないようにする必要があります:
import Vue from "vue"
// 他の mixin と衝突しないように
// フラグの名前は必ずユニークなものにしてください。
if (!Vue.__my_mixin__) {
Vue.__my_mixin__ = true
Vue.mixin({ ... }) // ミックスインを設定する
}


















































