1
0

More than 3 years have passed since last update.

Nuxt + Vue Property Decorator で ルーティングのパラメーターをバリデーションする

Posted at

TypeScript + Nuxt + Vue Property Decorator で開発していたところ、ルーティングのパラメーターバリデーションでハマったので備忘録として残します。

問題点

Nuxt.js でルーティングのパラメーターが数値であれば表示、それ以外なら Not Found とする、という処理を実現したい場合、以下のように記述すれば期待通りの結果になります。

export default {
  validate ({ params }) {
    return /^\d+$/.test(params.id)
  }
}

これを TypeScript + Vue Property Decorator を使って書く場合はどうすればいいでしょうか。
素直に以下のように記述すると、validate はユーザー定義のメソッドとして扱われてしまうため、動作してくれません。

import { Vue, Component } from 'vue-property-decorator';

@Component
export default class Index extends Vue {
  validate({ params }: { params: any }) {
    return /^\d+$/.test(params.id);
  }

  // その他処理
}

Vue Router 固有のメソッドを設定する

Component.registerHooksvalidate を追加すれば期待通りの動作をしてくれます。

import { Vue, Component } from 'vue-property-decorator';

// 追加
Component.registerHooks(['validate']);

@Component
export default class Index extends Vue {
  validate({ params }: { params: any }) {
    return /^\d+$/.test(params.id);
  }

  // その他処理
}

vue-property-decoratorComponent に認識させたい Vue プラグインのメソッドを追加すればOK
簡単ですね。

別解

別解というか、 Nuxt + TypeScript で開発する場合、こちらのほうがベターなのかもしれませんが、 vue-property-decorator の代わりに、 nuxt-property-decorator を利用します。

npm i -S nuxt-property-decorator
import { Vue, Component } from 'nuxt-property-decorator';

@Component
export default class Index extends Vue {
  validate({ params }: { params: any }) {
    return /^\d+$/.test(params.id);
  }

  // その他処理
}

Nuxt Property DecoratorVue Property Decorator のラッパーであり、内部でプラグインメソッドを設定しているので、 registerHooks() を記述する必要がなくなりました。

特に理由がないのであれば、 Nuxt Property Decorator を利用するほうが良さそうです。

参考

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