首页 > 解决方案 > 带参数的 Vue Router 动态段

问题描述

我正在尝试创建一个可以处理动态段并接受路由器道具(参数)的路由。像这样的东西:

{ path: '/peer:body?', name: 'peer', component: () => import('pages/peer.vue'), props: true }

并最终推动这样的路线:

this.$router.push({ path: '/peer/' + row.body, name: 'peer', params: { row: row } })

不幸的是,我只能使用path用作路由属性的动态段或用作路由属性的参数name,但不能同时使用。

标签: javascriptvue.jsvue-router

解决方案


First, as you already mentioned, when constructing "location descriptor object" for $router.push (or to prop of <router-link>), you can use path or name, not both at the same time (doesn't make sense to do so)

Second, you can pass params only when you use name (as described here - paragraph between first two code samples). To overcome this you can use query instead of params or build whole path including the params into the URL string.

And that brings me to the most important part of my answer. It seems as you are trying to pass a complex object as a route param (and into the target component props). While this is technically possible, it's not a good way of doing things. You have no place in your path definition where to put content of such parameter - it will work with push or clicking <router-link> where parameter is provided as an object, but when user accesses that URL directly (by copying and pasting URL for example), the page will be broken because prop parameter will be missing (as it cannot be extracted directly from the URL).

So my advise is to avoid that. Put your data into something like Vuex and instead of passing whole object by router, pass only some kind of identifier that can be included in the URL, extracted by Router and passed as a prop into target component. Then your target component should grab the Id and use it to query Vuex to get the data it needs...


推荐阅读