8
7

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でオリジナルPluginを作る方法

Last updated at Posted at 2019-12-28

TypeScriptでNuxtプラグインを書くけども

今回はVueインスタンスにインジェクトしないようなプラグインの方法です(ほとんどMiddlewareと大差ないように思えますが)
Vueインスタンスにインジェクトするパターン(this.$myPluginみたいなの)は公式サイトで説明があるので、そちらを参照してください。

プラグイン本体を書く

今回は単にrouteを表示するpluginを作る場合

pluginsディリクトリ以下にMyRoute.ts(お好きな名前で)などという名前をつけて以下のように書く

import { Plugin } from '@nuxt/types'

const myPlugin: Plugin = ctx => {
  console.log(ctx.route.path)
}
export default myPlugin

機能的には同じですが、
以下のようにContext型で書くこともでき、こちらの方がよりシンプルになります。


import { Context } from '@nuxt/types'

export default ({ route }: Context) => {
  console.log(route.path)
}

configを書き換える

nuxt.config.jsのpluginsプロパティを書き換える。これは通常通りです。

nuxt.config.js
plugins: [{ src: '~/plugins/MyRoute' }],

終わりに

ちょっと型注釈で困ったので備忘録に。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?