LoginSignup
20
14

More than 5 years have passed since last update.

Nuxt×TypeScriptでmiddlewareを使う

Last updated at Posted at 2018-08-20

はじめに

この投稿はこちらのページと同じことを記載しているだけです

ゴール

  • Nuxt.jsに
  • Typescriptを導入して
  • middlewareを使う

問題

こちらに記載されている通り、middlewareはVue標準でなくNuxt独自のプロパティである為、そのままjs→tsに変換してもうまく行かない

js:読み込める

index.vue
<script>
export default {
  middleware: 'auth'
}
</script>

ts:読み込めない

index.vue
<script lang="ts">
import { Vue, Component } from 'nuxt-property-decorator'

@Component({
  middleware: 'auth'
})
export default class extends Vue {}
</script>

Object literal may only specify known properties, and 'middleware' does not exist in type 'ComponentOptions<Vue...... というエラーが発生してしまう

解決策

ComponentOptionsを拡張してmiddlewareを追加する

index.d.ts
import Vue, { ComponentOptions } from "vue";

declare module "vue/types/options" {
  interface ComponentOptions<V extends Vue> {
    // This adds the `middleware` property to the existing `vue/types/options/ComponentOptions` type
    middleware?: string | string[];
  }
}

これで読み込めなかったtsでも読み込めるようになる

20
14
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
20
14