5

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

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

3 Comments

That's a step in the right direction, but ideally I would want to avoid adding the same thing to every single component and view..
@AdamSilva so, maybe plugins? And add mixins like this: Vue.mixin({ created: function () { // some logic ... } ... }) vuejs.org/v2/guide/plugins.html
Yeah, this is a nice workaround. I was hoping there would be a more direct approach to this.
1

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

Comments

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.