Skip to content

Instantly share code, notes, and snippets.

@Akryum

Akryum/example.js

Last active Oct 18, 2019
Embed
What would you like to do?
Vue Router - Navigate to parent named route
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' }
}
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
You can’t perform that action at this time.