Last active
June 13, 2022 17:28
-
-
Save Akryum/80b7e385361ee4321032174ac073cbd3 to your computer and use it in GitHub Desktop.
Vue Router - Navigate to parent named route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
const parents = getNamedParents(this.$router.options.routes, this.$route.matched) | |
if (parents.length) { | |
return { | |
name: parents[parents.length - 1].name, | |
} | |
} | |
return { name: 'home' } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function getNamedParents (routes, matched) { | |
let parent = null | |
const parents = [] | |
const parentPath = [] | |
for (const record of matched) { | |
let path = record.path | |
if (!path) { | |
path = '/' | |
} | |
if (parent) { | |
parentPath.push(parent.path) | |
} | |
if (parentPath.length) { | |
path = path.substr(parentPath.join('/').length + 1) | |
} | |
let next = routes.find(r => r.path === path) | |
if (next.path) { | |
parent = next | |
routes = next.children | |
if (!next.name && next.children) { | |
next = next.children.find(r => !r.path) | |
} | |
parents.push(next) | |
} else { | |
break | |
} | |
} | |
return parents.slice(0, parents.length - 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment