LoginSignup
8
3

More than 1 year has passed since last update.

Vue Routerのparamsの渡し方の変更点について

Posted at

これまでのparamsの渡し方

これまではcreateRouterで指定した各遷移先にpropsを定義し、画面遷移の際に指定した値をparamsに入れてpushしてあげれば十分だった。

router.js
export const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      name: 'first',
      component: FirstPage,
    },
    {
      path: '/second', 
      name: 'second',
      component: SecondPage,
      // ここで遷移元から受け取る変数を定義する。
      props: route => ({id: route.params.id, text: route.params.text}),
    }
  ]
})

しかし現在のVue Router(4.1.4)でこの書き方をすると以下のような警告が表示される。

遷移先に渡すはずの変数は破棄されてしまい、変数を受け取る遷移先のpropsにはundifinedが入ることになる。

[Vue Router warn]: Discarded invalid param(s) "id", "text" when navigating.

回避方法

引き続きparamsを使いたい場合はcreateRouterでのpathの定義を以下のように変更する。

router.js
export const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      name: 'first',
      component: FirstPage,
    },
    {
      path: '/second:id/:text', //pathの書き方を変更
      name: 'second',
      component: SecondPage,
      props: route => ({id: route.params.id, text: route.params.text}),
    }
  ]
})

またqueryを利用する方法もある。

router.js
export const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      name: 'first',
      component: FirstPage,
    },
    {
      path: '/second' //pathの書き方はそのまま
      name: 'second',
      component: SecondPage,
      //propsは不要
    }
  ]
})

遷移元からボタンクリックで遷移する場合は以下のようにparamsではなく、queryを記述する。

FirstPage.vue
<button
     @click="() => $router.push({ name: 'second', query: { id: '9999', text: 'XXXXXXX' } })">
</button>

遷移先では以下のように受け取ることができる。(createdで受け取る例)

SecondPage.vue
<script>
export default {
  name: 'SecondPage',
  data() {
    return {
      selectedId: '',
      inputText: '',
    }
  },
  created() {
    this.selectedId = this.$route.query.id
    this.inputText = this.$route.query.text
  }
}
</script>

参考

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