Reputation: 1011
Vue 2, Is there a lifecycle hook that actually refers to "finished rendering"? I want to put a loading screen when entering a page and it fades away and show the page content once Vue is finished loading everything, but I have tried most of the lifecycle hook but not working. Here is something I would try to do if updated
refers to "finished rendering":
updated(){
this.loaded()
},
methods:{
loaded(){
var vm = this;
this.loading = false;
}
}
If there is not such a lifecycle hook, what would you suggest me to do instead? Thanks
Upvotes: 6
Views: 9630
Reputation: 2137
Actually, your answer to your question is not what you have asked originally, the Vue instance is rendered in less than a second and it's not possible to use any hooks only to create userfriendly loader.
The case in using setTimeout
function is the only solution for this. But the component is ready in DOM a way earlier than 3 seconds.
The best approach for this purpose is to use loader component, where you will have setTimeout
in created
hook and after this time it will emit event to the parent.
So inside app you need only to import the loader component itself and when the event fires, change internal boolean data property to render another component v-if
Upvotes: 0
Reputation: 818
Probably the method you're looking for is mounted()
, this is fired when the vue component is ready. You can check the Vue life-cycle documentation here
so probably your Vue instance would look something like this:
var app = new Vue({
el: '#app',
/*
* When the instance is loaded up
*/
mounted: function () {
this.loaded()
},
methods: {
loaded: function () {
var vm = this
this.loading = false
}
}
})
Upvotes: 8
Reputation: 2106
To make sure that all child components have also been mounted, use vm.$nextTick
- much cleaner than a setTimeout:
mounted: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
}
Source: https://v2.vuejs.org/v2/api/#Options-Lifecycle-Hooks
Upvotes: 2
Reputation: 1011
As I cannot find that there is a specific lifecycle hook or other Vue-specified method to hook the point where everything is finished rendering, I used the basic js code as well as estimation of time needed for loading all the things with codes as following:
mounted(){
this.loaded()
},
methods:{
loaded(){
var vm = this;
setTimeout(function(){
vm.loading = false
}, 3000);
}
}
Hope there will be someone who is strong at Vue and provide a new answer to hook it more accurately.
Upvotes: 0