Vue 路由传参的方式

197 阅读1分钟

通过路由的 path 设置

路由配置:
{
  path: '/pre/:id',
  name: 'pre',
  component: () => import('../views/PreView.vue'),
}

跳转:
this.$router.push({
  path: `/pre/${id}`
})

组件内接收:
this.$route.params.id

跳转时增加 params 配置项

路由配置:
{
  path: '/pre',
  name: 'pre',
  component: () => import('../views/PreView.vue'),
}

跳转:
this.$router.push({
  path: '/pre',
  name: 'pre',
  params: {
    id: 12
  }
})

组件内接收:
this.$route.params.id

跳转时增加 query 配置项

路由配置:
{
  path: '/pre',
  name: 'pre',
  component: () => import('../views/PreView.vue'),
}

跳转:
this.$router.push({
  path: '/pre',
  name: 'pre',
  query: {
    id: 12
  }
})

组件内接收:
this.$route.query.id

params 和 query

  • 当使用query参数时,参数是配置在URL中的,刷新时参数不会丢失
  • 当使用params参数时,参数是隐藏不可见的,刷新时参数会丢失