Skip to content
Advertisement

How to detect when vue component is after update function by property?

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.

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement