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

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

我正在尝试将 'joke.id' 作为参数发送到路由器:

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

相关路线为:

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

但是我在控制台中得到了这个:

Module build failed: SyntaxError: Unexpected token

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

我该如何解决这个问题?

push 函数内不需要花括号。你的代码应该是这样的:

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

您可以使用以下语法将参数传递给路由器:

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

如果您已经命名了路线,则可以改用此语法:

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

阅读有关使用 Vue Router 进行编程导航的更多信息here

给你!

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

您可以拥有任意数量的参数。 您还可以从 HTML 组件应用相同的技术:

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

仅确保目的地名称与您在路线中指定的名称相同。

您不一定非要使用 router-link 因为大多数当前组件都支持 :to 属性,尤其是 Vuetify.

您必须绑定路由器参数

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

并在您的索引路由器中

path:'/user/:id'