Created
June 22, 2018 11:53
-
-
Save Shtian/dac4b77f5dbaf2042c9c0715dcb42d73 to your computer and use it in GitHub Desktop.
VueJs set body class router middleware
This file contains hidden or 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
// 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