Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue - remove latest child path

so I currently have my router paths set up as such:

{
    component: List,
    name: "account-list",
    path: "list/:id",
    // alias: "list/:id/edit_item/:item_id",
    children: [
        {
            path: "edit_item/:item_id",
        },
        {
            path: "*",
            redirect: "/account/list/:id"
        }
    ]
}

And let's say we have a url like this: http://localhost:8080/#/account/list/5bb17bdec7fb946609ce8bd4/edit_item/5bbc2d12aded99b39c9eadb9

How would I turn this into:

http://localhost:8080/#/account/list/5bb17bdec7fb946609ce8bd4

I am currently using

this.$router.back()

Which generally works well, but if I were to have accessed another item by directly pasting in its url, this.$router.back() would just revisit the previous url.

So is there a surefire way to guarantee that I would remove the child path?

like image 768
A. L Avatar asked Oct 09 '18 04:10

A. L


2 Answers

Vue router will maintain current params when navigating so you should be able to navigate to the named parent route.

For example

this.$router.push({ name: 'account-list' })

The current :id param will be re-used.

If you wanted to make it dynamic, you could work your way up the current route's matched array. For example, to go to the current route's named parent

this.$router.push({
  name: this.$route.matched[this.$route.matched.length - 2].name 
})

This will only work on nested routes of course as the matched length for top-level routes is only 1.


For non-named routes you must construct the full path with all params interpolated into the string. You could do it by getting the destination routes path property and substituting param tokens with those in this.$route.params but that's going to get messy. Eg

// get parent path property
let path = this.$route.matched[this.$route.matched.length - 2].path
let realPath = path.replace(/:\w+/g, param => 
    this.$route.params[param.substr(1)])
this.$router.push(realPath)

This won't work if your paths use advanced pattern matching.

like image 50
Phil Avatar answered Sep 25 '22 08:09

Phil


You can move your child route up one level, so that it is not a child anymore. That way the id would show up in the this.$router.params object.

[
  {
    path: 'list/:id',
    component: List,
    name: "account-list"
  },
  {
    path: 'list/:id/edit_item/:itemid',
    component: Form,
    name: "account-form"
  }
]

You can do a do a $router.replace to replace the current path.

const id = this.$router.params['id'];

this.$router.replace({
  name: 'account-form',
  params: { id }
})
like image 39
tomaj Avatar answered Sep 23 '22 08:09

tomaj