1
1
mirror of https://github.com/aelve/guide.git synced 2024-12-25 13:51:45 +03:00
guide/front/client/entry.client.ts
avele da9031a6ba
Feat/preload pages on client and progress bar (#266)
* progress bar

* Using saved scroll when going forward/back  in browser

* router intance added to context of client side asyncData functions
2019-02-10 16:00:50 +04:00

71 lines
1.9 KiB
TypeScript

import Vue from 'vue'
import 'reflect-metadata'
import 'babel-polyfill'
import _get from 'lodash/get'
import { createApp } from './app'
const { app, router, store } = createApp()
const STATE_KEY = '__INITIAL_STATE__'
if (window[STATE_KEY]) {
store.replaceState(window[STATE_KEY])
}
router.onReady(() => {
registerBeforeResolve()
app.$mount('#app')
})
function registerBeforeResolve () {
router.beforeEach(async (to, from, next) => {
store.commit('tooglePageLoading')
if (!to.matched.length) {
store.commit('tooglePageLoading')
next()
return
}
const propsOption = to.matched[0].props.default
const props = propsOption
? typeof propsOption === 'function'
? propsOption(to)
: typeof propsOption === 'object'
? propsOption
: to.params
: {}
const routeComponent = to.matched[0].components.default
const matchedRootComponent = routeComponent.cid // Check if component already imported
? routeComponent
: (await routeComponent()).default
const matchedComponentsAndChildren = getComponentAndItsChildren(matchedRootComponent)
await Promise.all(matchedComponentsAndChildren.map(component => {
const asyncData = component.options.methods.asyncData
if (typeof asyncData === 'function') {
return asyncData.call({
$store: store,
$router: router,
...props
})
}
}))
store.commit('tooglePageLoading')
next()
})
}
function getComponentAndItsChildren (component, result?) {
if (!result) {
result = []
}
if (!result.includes(component)) {
result.push(component)
}
const children = Object.values(component.options.components)
// Parent component is also presents in components object
.filter(x => x !== component)
children.forEach(x => getComponentAndItsChildren(x, result))
return result
}