CamelCase
CamelCase

Reputation: 75

how can I change only a param like an id in my URL

I have a have a list of links inside a childcomponent which is integrated in different pages and if I click on a link, I need to get an id back, but I need to keep the current URL with the new id to call another method.

this.$router.push({path: '/page/', params: {id:id}})
this.$router.push({path: '/otherpage/', params: {id:id}})

I tried several things which are not working, like

this.$router.push({path: this.$router.currentRoute, params: {id:id}})

to get the following on different pages

http://domain/page/1

or

http://domain/otherpage/1

if I hardcode the path it works with:

this.$router.push(`/page/${id}`)

but I like to reuse the component on any page

thanks to Igor I ended up with the following:

  const path = `/${this.path}/${node.id}`
  if (this.$route.path !== path) this.$router.push(path)

thanks

Upvotes: 0

Views: 2141

Answers (1)

Igor Moraru
Igor Moraru

Reputation: 7729

From vue-router docs:

Note: params are ignored if a path is provided... https://router.vuejs.org/guide/essentials/navigation.html

Instead of providing the path, you should call this.$router.push() with the route name, and the desired params.

For your example:

this.$router.push({name: this.$router.currentRoute.name, params: {id:id}})

This approach assumes that your routes are named, like this:

const routes = [
  {
    path: "/page/:id",
    component: () => import('/path/to/component.vue'),
    name: "nameOfTheRoute",
    // other attributes
  },
  //...
]

Upvotes: 1

Related Questions