8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nuxt + TypeScriptでプラグインの定義を追加する

Posted at

nuxt2.1.0, node10.11.0
2018.10.19現在


独自のプラグインを書いた場合、vueのTypeScript定義の拡張が必要になる。

単純なプロパティの追加は公式docに記載があるが、独自クラスのインスタンス等を設定したい場合はどうするのがベスト・プラクティスなのか。
https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins

とりあえず作ってみた形のもの

~/plugin/some-plugin.ts
// plugin classの定義
export class SomePlugin {
  private someStatus: string = '';

  constructor(status: string) {
    this.someStatus = status
  }

  getStatus(): string {
    return this.someStatus
  }
}

// plugin
export default ({ app }, inject) => {
  // ... get status logic
  const st = 'hoge';

  inject('somePlugin', new SomePlugin(st));
};

pluginファイルでクラス定義して、、、

some.d.ts
declare module '*.vue' {
  import { SomePlugin } from '~/plugins/some-plugin.ts';

  module 'vue/types/vue' {
    interface Vue {
      $somePlugin: SomePlugin;
    }
  }
}

d.tsファイルでvue定義を拡張し、、、

some.vue
@Component
export default class SomeVue extends Vue {
  getSomeStatus(): string {
    return this.$somePlugin.getStatus()
  }
}

実際のvue componentで使う。

これで動きはしたけどもっといいやり方ありそう。

8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?