如何使用 vue-router 参数 [英] how to use vue-router params
问题描述
我是 vue 的新手,现在正在使用它的路由器.我想导航到另一个页面,我使用以下代码:
I'm new to vue now working with its router. I want to navigate to another page and I use the following code:
this.$router.push({path: '/newLocation', params: { foo: "bar"}});
然后我希望它在新组件上
Then I expect it to be on the new Component
this.$route.params
这不起作用.我也试过:
This doesn't work. I also tried:
this.$router.push({path: '/newLocation'});
this.$router.push({params: { foo: "bar"}});
我稍微检查了源代码并注意到此属性被新对象 {} 覆盖.
I've inspected the source code a bit and noticed this property gets overwritten with new object {}.
我想知道 params 的用途是否与我想象的不同?如果没有,如何使用?
I'm wondering is the params use is other than I think? If not, how to use it?
提前致谢
推荐答案
既然你想将参数传递给相应路由的组件,你路由对象的路径属性应该有一个由 :
表示的动态段后跟 params 对象中键的名称
Since you want to pass params to the component of the respective route you route object's path property should have a dynamic segment denoted by :
followed by the name of the key in your params object
所以你的路线应该是
routes: [
{path: '/newLocation/:foo', name: 'newLocation', component: newComponent}
]
然后以编程方式导航到组件,您应该这样做:
Then for programmatically navigating to the component you should do:
this.$router.push({name: 'newLocation', params: { foo: "bar"}});
看到我使用的是路由的 name
而不是 path
,因为您正在通过属性 params
传递参数.
See that I am using name
of the route instead of path
as you are passing params by the property params
.
如果你想使用 path
那么它应该是:
if you want to use path
then it should be:
this.$router.push({path: '/newLocation/bar'});
通过路径方法,params 将自动映射到 $route.params
上的相应字段.
by the path approach the params will automatically map to corresponding fields on $route.params
.
现在,如果您在新组件中console.log(this.$route.params)
,您将获得对象:{"foo": "bar"}
Now if you console.log(this.$route.params)
in your new component you will get the object : {"foo": "bar"}
这篇关于如何使用 vue-router 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!