Last active
April 29, 2020 05:32
-
-
Save kayvazov/64f6709b8350962b21fdebbc9b57e083 to your computer and use it in GitHub Desktop.
asyncData.js for Vue ( without Nuxt.js )
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
// asyncData.js | |
export default ({ store, router }) => async (to, from, next) => { | |
const matched = router.getMatchedComponents(to); | |
const prevMatched = router.getMatchedComponents(from); | |
let diffed = false; | |
const activated = matched.filter((c, i) => { | |
const isActivated = diffed || (diffed = (prevMatched[i] !== c)); | |
return isActivated; | |
}); | |
if (!activated.length) { | |
// push last match for loading asyncData | |
activated.push(matched[matched.length - 1]); | |
} | |
const asyncDataHooks = [router.app.$options, ...activated] | |
.filter((_) => _) | |
.map((c) => c.asyncData) | |
.filter((_) => _); | |
if (!asyncDataHooks.length) { | |
next(); | |
return; | |
} | |
try { | |
const hooks = asyncDataHooks | |
.map((hook) => hook({ store, router, route: to })) | |
.filter((_) => _); | |
await Promise.all(hooks); | |
next(); | |
} catch (error) { | |
if (process.env.NODE_ENV !== 'production') { | |
console.warn('Error while asyncData:'); | |
console.error(error); | |
} | |
next(); | |
} | |
}; | |
// main index.js | |
router.beforeResolve(asyncData({ store, router })); | |
// in component | |
data: () => ({ ... }), | |
asyncData({ store }) { | |
return store.dispatch('actionName') | |
}, | |
methods: { ... } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment