Home > other >  Default lifecycle hook in Vue
Default lifecycle hook in Vue

Time:08-05

I want to run the same function as a beforeMount hook in each component in my Vue project by default. That is, if I don't declare this hook in a component, it will print 'Default hook', for example. I need something like an option when creating new Vue instance. How can I do this?

If that's impossible, can I replace all beforeMount hooks with one function?

UPD.
As far as I know, global mixins are always run. I don't want to run them if the same hook is declared in a component. But if it's not, the default hook should be used.

CodePudding user response:

This can be achieved with global mixin by checking if its beforeMount is the only one defined in options:

app.mixin({
  beforeMount: function globalBeforeMount() {
    if (
      this.$options.beforeMount === globalBeforeMount ||
      Array.isArray(this.$options) && this.$options.length === 1 && this.$options[0] === globalBeforeMount);
    )
      return;
      ...
  }
});

This is XY problem, it's a wrong design choice that needs to be avoided. Generally, it's a bad practice to provide global behaviour for local purposes. A global mixin affects third-party components that weren't suited to be used with it. On the other hand, third-party libraries may expose their own global mixins that may be incompatible with user mixins, in this case this will result in custom hook being never triggered.

CodePudding user response:

I'd recommend you to stay away from modifying source code that is not your own simple because of the possible braking changes on each version release.

But vue ha global mixins and custom bindings that you register on app initialization and will run on each component. 1I would recommend against that though just because of the extra work your app will be doing on components that do not benefit from that method.

instead make a wrapping processor that you can use in a similar way as the vue built in 'transition' component always good to be deliberate with what you do.

Can't give any examples atm, will do an edit tomorrow

  • Related