0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Vue]プラグインってな~に?

0
Posted at

なければ作ってしまえばいいのよ!

かの有名な涼宮ハルヒはいいました。

ないんだったら自分で作ればいいのよ!

とりあえず 作ってみれば いいじゃない、どうも廃人俳人なえ~すけさんです。

作ってみたら案外簡単

Vueにはアプリケーション全体に対して機能を拡張する仕組みを提供できるプラグインと言う機能があるって知ってます?

main.ts(js)とかでVueを初期化する際にapp.use()で登録することで、
アプリの初期化時に一度だけ実行され、グローバルな設定や機能を注入できるアレです。
※app.use(pinia)とかで出てくるアレ

基本形

my-plugin.ts
export default {
  install(app, options) {
    // 初期化処理
  }
}

使う時は

main.ts
import MyPlugin from './plugins/my-plugin'

const app = createApp(App)
app.use(MyPlugin, { /* options */ })

プラグインでできること

主に以下のような「アプリ全体に関わる操作」が可能です。

1. グローバルプロパティの追加

app.config.globalProperties.$api = apiClient

どのコンポーネントからでも this.$api でアクセス可能

2. 依存注入(provide / inject)

app.provide('api', apiClient)

inject('api') で取得できる(テストしやすい)

3. グローバル設定の変更

app.config.errorHandler = (err) => {
  // 共通エラーハンドリング
}

4. グローバルコンポーネント / ディレクティブの登録

app.component('MyButton', MyButton)
app.directive('focus', { /* ... */ })

逆に、プラグインがやるべきでないこと

ダメ、ゼッタイ

画面固有のロジック

  • 特定画面だけで使う処理
  • UIに強く依存する処理

スコープが広すぎる

単なる関数の共有

// NG:ただのユーティリティ
app.use(formatDate)

Composableやutility関数で十分

状態を乱雑にグローバル化する

app.config.globalProperties.$user = ref(null)

依存関係が見えなくなる
そもそもこんなのPinia使えって話ですが。。。

Composableとの違い

前の記事で書いたComposableとの違いをザックリ言うとこんな感じ

観点 Composable プラグイン
スコープ 局所 グローバル
実行タイミング 呼び出し時 アプリ初期化時
主な用途 ロジックの再利用 仕組み・基盤の提供
依存管理 import provide/inject

要は

プラグインは「全体に効く仕組み」を注入するもの

この前提を踏まえた上で、次の投稿あたりでComposableで十分なケース vs プラグインにすべきケースを書いてみようかと。
※長くなるので投稿分けるわ。。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?