Last active
December 18, 2018 18:48
-
-
Save trainiac/f01ffa71047404fe7e9a3c40910f33bf to your computer and use it in GitHub Desktop.
An example of using custom route hooks in a vue universal web application's client entrypoint.
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
const store = createStore() | |
// data populated from server | |
store.replaceState(window.__INITIAL_STATE__) | |
const router = createRouter() | |
const routerReady = new Promise(resolve => { | |
router.onReady(resolve) | |
}).then(() => { | |
// onReady hook | |
// request all the inital route's lazy data without blocking rendering | |
router.getMatchedComponents(router.currentRoute).forEach(component => { | |
// allow hook to be optional | |
if (component.lazyData) { | |
component.lazyData(store, router.currentRoute, {}) | |
} | |
}) | |
// subcribe to the beforeResolve hook to | |
// request permissions for subsequent navigation | |
router.beforeResolve((to, from, next) => { | |
const matched = router.getMatchedComponents(to) | |
const permissionPromises = matched.map(component => { | |
// allow hook to be optional | |
if (component.permissions) { | |
return component.permissions(store, to, from) | |
} | |
return Promise.resolve() | |
}) | |
Promise.all(permissionPromises) | |
.then(() => { | |
next() | |
}) | |
.catch(err => { | |
console.log(err) | |
next(err) | |
}) | |
}) | |
// subcribe to the afterEach hook to | |
// request critical data and lazy data for subsequent navigation | |
router.afterEach((to, from) => { | |
const matched = router.getMatchedComponents(to) | |
matched.forEach(component => { | |
// allow hook to be optional | |
if (component.criticalData) { | |
component.criticalData(store, to, from) | |
} | |
}) | |
matched.forEach(component => { | |
// allow hook to be optional | |
if (component.lazyData) { | |
component.lazyData(store, to, from) | |
} | |
}) | |
}) | |
}) | |
const app = createApp(store, router) | |
routerReady.then(() => { | |
app.$mount('#app') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment