Skip to content

Instantly share code, notes, and snippets.

@Shtian
Created June 22, 2018 11:53
Show Gist options
  • Save Shtian/dac4b77f5dbaf2042c9c0715dcb42d73 to your computer and use it in GitHub Desktop.
Save Shtian/dac4b77f5dbaf2042c9c0715dcb42d73 to your computer and use it in GitHub Desktop.
VueJs set body class router middleware
// Set body class from meta property bodyClass
router.beforeEach((to, from, next) => {
const getBodyClass = (acc, routeRecord) => {
if (routeRecord.meta && routeRecord.meta.bodyClass) { acc.push(routeRecord.meta.bodyClass) }
return acc
}
const prevBodyClass = from.matched.reduce(getBodyClass, [])
const newBodyClass = to.matched.reduce(getBodyClass, [])
prevBodyClass.forEach(c => {
document.body.classList.remove(c)
})
newBodyClass.forEach(c => {
document.body.classList.add(c)
})
next()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment