LoginSignup
3
1

More than 1 year has passed since last update.

Nuxt.jsのpluginについて

Last updated at Posted at 2021-08-03

目次 

1.はじめに
2.pluginとは
3.pluginの実装方法
4.関数の呼び出し
5.おわりに

1. はじめに

Vuexでmixinを使いたかったのですが、調べてみるとVuexでmixinを使用するという記事が見当たらず、その代わりにpluginで使用する記事がたくさん出てきたのでpluginを使用して共通メソッドを作成してみました。

2. pluginとは

Nuxt.jsの拡張に使えます。
共通メソッドを定義してmixinsで読み込ませたり、ルートに追加することでthisで呼び出せたりします。
今回の場合は共通メソッドをplugionにまとめてVuexで使用したいと思います。

3. pluginの実装方法

①ファイル作成
/plugin にファイルを作成します。ファイル名は何でも構いません。
スクリーンショット 2021-08-03 8.27.55.png

②ファイルにcomponentやstoreで使用したい関数を定義します。
書き方例 Nuxt公式参照

export default ({ app }, inject) => {
  // Vue、コンテキスト、ストアに$hello(msg)を挿入します。
  inject('hello', msg => console.log(`Hello ${msg}!`))
}

export default ({ app }, inject) => {ここでrootに追加する宣言を行いどこからでも呼び出し可能にします。

inject('hello', msg => console.log(`Hello ${msg}!`))inject(任意の関数名, 引数 => 関数)の形にすることで実際にrootに追加する関数を定義できます。

③rootに直接追加するため、importは必要ありませんがnuxt.config.jsで読み込ませる必要があります。
スクリーンショット 2021-08-03 13.04.19.png

4. 関数の呼び出し

this.$メソッド名で呼び出すことができます。storeのactionsやmutationsを実行する感覚に近いですね。
template内で使用したい時はreturnを使用してmethodsで定義してあげます。

export default {
  methods: {
    greeting () {
    this.$hello('tarou')
    // console.log 'Hello tarou!'
   }
  }
}

また、同じようにsore内でもメソッドを使用することができます。

export const actions = {
  setSomeValueToWhatever({ commit }) {
    this.$hello('store action') //共通メソッド
    const newValue = 'whatever'
    commit('changeSomeValue', newValue)
  }
}

5. おわりに

色々な記事を見ましたが公式が一番わかりやすかったです。
よくわからない方は公式の実装例を見ると理解が深まるかと思います。

Nuxt公式参照

3
1
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
3
1