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