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?
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.
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 }
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With