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.registerHooks
に validate
を追加すれば期待通りの動作をしてくれます。
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-decorator
の Component
に認識させたい 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 Decorator
は Vue Property Decorator
のラッパーであり、内部でプラグインメソッドを設定しているので、 registerHooks()
を記述する必要がなくなりました。
特に理由がないのであれば、 Nuxt Property Decorator
を利用するほうが良さそうです。