Adam Silva
Adam Silva

Reputation: 1047

VueJS Adding to lifecycle hooks on every component

So I have a loader screen in my app, and the idea is to show the loader screen on the beforeCreate hook so the user can't see the stuff being rendered, and then on the mounted hook remove the loader screen.

This is fun and nice for when you have two or three view/components, but currently my app has a lot more than that, and adding it to each component/view doesn't make much sense for me.

So I was wondering, is there any way to add something to the beforeCreate and mounted hooks on a global scope. Something like this:

main.js

Vue.beforeCreate(() => {
    //Show the loader screen
});

Vue.mounted(() => {
    //Hide the loader screen
});

That way it would be applied to every component and view

Upvotes: 5

Views: 3759

Answers (2)

Vladislav  Gritsenko
Vladislav Gritsenko

Reputation: 813

You can use mixins for this purposes, and import in components.

//mixins.js
export default {
  beforeCreate() {},
  mounted() {}
}

And in component add mixins: [importedMixins]

You will have access to 'this'.

Actualy you can use and vuex to (mapGetters, mapActions etc.)

If you don't want include mixins in every component, try to use vue plugins system (https://v2.vuejs.org/v2/guide/plugins.html):

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = function () {
    // something logic ...
  }

  // 2. add a global asset
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // something logic ...
    }
    ...
  })

  // 3. inject some component options
  Vue.mixin({
    created: function () {
      // something logic ...
    }
    ...
  })

  // 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // something logic ...
  }
}

And use your plugin like this Vue.use(MyPlugin, { someOption: true })

Upvotes: 9

Adam Orłowski
Adam Orłowski

Reputation: 4464

There is something very silimar to your request in vue-router. I've never used afterEach but beforeEach works perfectly.

router.beforeEach((to, from, next) => {
  /* must call `next` */
})

router.beforeResolve((to, from, next) => {
  /* must call `next` */
})

router.afterEach((to, from) => {})

Here is a documentation

There is also a hook called 'beforeRouteEnter'.

Link to beforeRouteEnter docs

Upvotes: 1

Related Questions