Vue: Is that any way to shared a global var and function of parent to all child components?

Created on 14 Sep 2015  路  2Comments  路  Source: vuejs/vue

Is that any way to shared a global var and function of parent to all child components?

Not by prop and inherit.

For example, I want to define my general output error function to log the promise catch error, but I have to import this output error function from helper.js in all components. When the page system is huge, it is hard to maintain. What I want is define a global var or method in parent, all child components can use it.

Now my temporary solution is to user webpack-stream or gulp to package the helper.js with main file. But should there be a way in Vue to manage the global var and function in the component symtem?

Most helpful comment

There are several ways:

  1. Like what you did, import helper.js when you need it. This is actually the recommended approach - although repetitive, it clearly shows where the method comes from.
  2. Just add it to Vue.prototype. For example, Vue.prototype.$onPromiseError = ... so all instances can just this.$onPromiseError(err). Better yet, group all your global helpers into a mixin, so you know where to look for them and maintain them.
  3. Make it a separate global, like you did. This is fine when the scope is small and you put everything under your own namespace object.

All 2 comments

There are several ways:

  1. Like what you did, import helper.js when you need it. This is actually the recommended approach - although repetitive, it clearly shows where the method comes from.
  2. Just add it to Vue.prototype. For example, Vue.prototype.$onPromiseError = ... so all instances can just this.$onPromiseError(err). Better yet, group all your global helpers into a mixin, so you know where to look for them and maintain them.
  3. Make it a separate global, like you did. This is fine when the scope is small and you put everything under your own namespace object.

@yyx990803 Big thank-you! I was trying to directly assign properties to the Vue instance and going nuts. :smile:

Was this page helpful?
0 / 5 - 0 ratings