简体   繁体   English

如何在方法函数中将参数传递给 vue.js 路由器?

[英]How to pass parameter to vue.js router in a method function?

I'm trying to send 'joke.id' as parameter to the router:我正在尝试将“joke.id”作为参数发送到路由器:

edit: function(joke) {
    this.$router.push({ '/edit/' + joke.id }); 
}

The relevant route is:相关路线是:

{path: '/edit/:id', component: editJoke, name: 'editJoke'},

However I get this in the console:但是我在控制台中得到了这个:

Module build failed: SyntaxError: Unexpected token模块构建失败:SyntaxError: Unexpected token

this.$router.push({ '/edit/' + joke.id }); 
  |                          ^

How can I fix this?我怎样才能解决这个问题?

You can pass parameters to the router by using this syntax:您可以使用以下语法将参数传递给路由器:

edit: function(joke) {
    this.$router.push('/edit/' + joke.id)
}

If you have named your route you can use this syntax instead:如果您已命名路线,则可以改用以下语法:

edit: function(joke) {
    this.$router.push({ name: 'edit', params: { id: joke.id }})
}

Read more about programmatic navigation with Vue Router here .在此处阅读有关使用 Vue Router 进行编程导航的更多信息。

There's no need for curly braces inside the push function. push函数中不需要大括号。 Your code should be like this:你的代码应该是这样的:

this.$router.push('/edit/' + joke.id); 

Here you go!干得好!

 this.$router.push({name: 'DESTINATION', params: {VAR1: 'VALUE1', VAR2:'VALUE2'}})

You can have as many parameters as you want as such.您可以拥有任意数量的参数。 You can also apply the same technique from your HTML components:您还可以在 HTML 组件中应用相同的技术:

<router-link :to="{name: 'DESTINATION', params: {VAR1: 'VALUE1', VAR2: 'VALUE2'}}" />

Only make sure the destination name is equivalent to the name you specified inside your routes.只需确保目的地名称与您在路线中指定的名称相同。

You don't necessarily have to use router-link since most of the current components support the :to attribute, especially Vuetify .您不一定必须使用 router-link,因为大多数当前组件都支持 :to 属性,尤其是Vuetify

You have to bind your router params你必须绑定你的路由器参数

<router-link :to="{name:'show.user',params:{id:user.id} }">your links</router-link>

and in your index router并在您的索引路由器中

path:'/user/:id'

if you want to use params you need to use name and not path:如果要使用参数,则需要使用名称而不是路径:

<nuxt-link :to="{name: 'post-detail-id', params: { id:idPost } }">{{title}}</nuxt-link>

You can see the name for each route into .nuxt/router.js您可以在 .nuxt/router.js 中看到每个路由的名称

REFRENCE LINK: Solution参考链接: 解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM