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

Viewed 16769

I'm trying to send 'joke.id' as parameter to the router:

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

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

How can I fix this?

5 Answers

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.

There's no need for curly braces inside the push function. 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:

<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.

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

REFRENCE LINK: Solution

Related