LoginSignup
5
1

More than 3 years have passed since last update.

VueのRouterでURLのパラメータの型をstringから変更する

Last updated at Posted at 2020-03-19

例えばユーザーデータ更新APIリクエストでURLのIDとか使って引数に渡す時に,

this.$route.params.userId

↑みたいに取得するとstringでしか受け取れず
毎回number型に変更するのが冗長な気がしてたので
router側で変更する方法ないかなぁって調べたけど
なかなか出てこなかったけどやっと見つけたのでメモ

修正前

修正前のrouterでの設定が↓だとして,

{
  path: 'userEdit/:userId',
  name: 'userEdit',
  component: () => import('./views/UserEdit.vue'),
},

修正後

propsという項目でパラメータの型を変更することができる
routerから先にparamsを取り出して,キャストしてpropsにセットするというやり方

{
  path: 'companyList/:companyId',
  name: 'companyEdit',
  component: () => import('./views/CompanyEdit.vue'),
  props: (route) => ({userId: Number(route.params.userId)}),
},

コンポーネントでの受け取り方

後はコンポーネントでPropで受け取るだけ
自分の環境だと↓で受け取れる

@Prop()
private userId!: number;

意外にもクソ簡単だった。。。。。

おわり

参考資料

VueRouter基本ルーティング記法まとめ

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