Reputation: 7370
I have several Vue components (realized as .vue
files process by Webpack & the Vue Loader) that need to be synchronized (i.e. display / allow interaction of a video stream). Some of them require some initialization effort (i.e. downloading meta data or images).
Can I somehow delay a component until that initialization is ready? Perfect would be if I could wait for a Promise to be fulfilled in a lifecycle hook like beforeCreate
.
I know about asynchronous components, but as far as I understand all I could do is to lazy-load that component, and I still would have a way to wait for a certain initialization.
Upvotes: 2
Views: 1809
Reputation: 27729
You can do that on route level.
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
doSomeRequests()
.then(() => (next()))
}
}
]
})
doSomeRequests
is a function that is doing some async code. When that async code finish
then you call next()
to allow vue router to enter the component which corresponds to the url. In the example the component Foo
My suggestion would be to show a loader in the component.
<template>
<!-- code -->
<LoaderComponent :loading="loading" />
<!-- code -->
</template>
And the script part:
<script>
export default {
// code
data: () => ({
loading: false
}),
created () {
this.loading = true
doSomeRequests()
.then(<!-- code -->)
.finally(() => (this.loading = false))
}
}
</script>
Upvotes: 4