109
87

More than 3 years have passed since last update.

Nuxt.jsで異なるコンポーネントから共通で利用できる関数を定義する(inject編)

Last updated at Posted at 2019-10-23

異なるコンポーネントから共通で利用できる関数を定義したかったので、試してみました。

以前の記事ではmixinを使って実現しましたが、この方法では asyncDatafetch 内で共通の関数を利用できませんでした。
そのため、今回はinjectを使って実現しています。

この方法では、 asyncDatafetch 等のSSR時も関数を利用できるため、こちらの方が良いかもしれません。

共通の関数を定義する

plugins/ 内に utils.js というファイルを作成し、ここに関数を定義していきます。
今回は例として hoge()fuga() という、2つの関数を定義するものとします。

使用する際は this.$huga() のように記述します。

plugins/utils.js
const hoge = () => {
  return "hoge";
}

const fuga = () => {
  return "fuga";
}

export default ({}, inject) => {
  inject('hoge', hoge);
  inject('fuga', fuga);
}

nuxt.config.jsに設定を追加

nuxt.config.js に設定を追加します。

nuxt.config.js
plugins: [
  '@/plugins/utils'
],

コンポーネントからの利用

<template> 内での利用は、関数名の前に $ を付けて呼び出します。

pages/index.vue
<template>
  <button @click="$hoge()">hogeを実行</button>
</template>

<script> 内の asyncDatafetch 内で使用したい場合は、 context から呼び出します。
こちらも関数名の前に $ が付きます。

pages/index.vue
<script>
export default {
  asyncData(context){
    context.app.$hoge();  // ここで呼び出し
  }
}
</script>

SSR時以外は、 this.$hoge() のように呼び出します。

pages/index.vue
<script>
export default {
  methods: {
    hoge() {
      return this.$hoge();  // ここで呼び出し
    }
  }
}
</script>

便利!

TypeScriptでも同じように利用したい場合は、こちらを参考にしてください。
参考: Nuxt.js + TypeScript で injectを利用した関数の呼び出しを定義する

109
87
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
109
87