0

I need to display a spinner in vue for every component (this is the requirement).

For that I think about to do v-if="loading" inside component HTML.

My question is how to detect when component is loading complete? (meaning after the DOM is rendered, and the data-bind is resolved to the DOM elements)

According to Vue lifecycle when update function is trigger then the render is complete.

So for that I'll need to implement for every component update function that change the loading to false. is there eazy way to do that? for example one place to write the update function? can I do that without implement extends? any sophisticated way to do that?

What I need for example is this.loading available in Vue instance.

1 Answer 1

1

Of course you can do it. Vue mixins come in rescue.

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

Notice that you should use mounted hook if you want to track when the component is inserted into DOM.

Called after the instance has been mounted, where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.

mixin.js:

export default {
  data() {
    return {
      loading: true
    }
  },
  mounted() {
    console.log('I have been mounted')
    this.loading = false
  }
}

And then register that mixin globally, so it will be available in all components:

import mixin from './mixin'

Vue.mixin(mixin)
Sign up to request clarification or add additional context in comments.

2 Comments

One more thing please: Is there a way to know when all the children components are rendered(after mounted)? for example I have Person component, and I have children (not by v-for) and I want to know from Person component when the children is ready and rendered. there is a way to do that?
Note that mounted does not guarantee that all child components have also been mounted. If you want to wait until the entire view has been rendered, you can use vm.$nextTick inside of mounted. ref.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.