Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Adding to lifecycle hooks on every component

Tags:

vue.js

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

like image 460
Adam Silva Avatar asked Aug 10 '18 11:08

Adam Silva


1 Answers

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 })

like image 166
Vladislav Gritsenko Avatar answered Sep 30 '22 13:09

Vladislav Gritsenko