Eddie Dane
Eddie Dane

Reputation: 1569

Vue - make helper for root component and all child component

Please is there a way to create a helper function on a root component in vue and also make the function accessible in all child components?

Upvotes: 1

Views: 257

Answers (2)

Dmitry
Dmitry

Reputation: 133

You can create helper functions and use it as a plugin. In case of you are using nuxt.js, you can create helpers.js in plugins and register it in nuxt.config.js file.

import Vue from 'vue'
import helpers from './helpers'

const plugin = {
  install () {
    Vue.prototype.$helpers = helpers
  }
}

Vue.use(plugin)

In helpers.js, you can define all helper functions.

export default { 
  cloneObj(val) {
    return JSON.parse(JSON.stringify(val));
  }
};

Then you can use it in any child components like this:

this.$helpers.cloneObj()

Upvotes: 3

Ali Ataf
Ali Ataf

Reputation: 689

You need to store it in a separate file because it's frustrating to pass it as a prop from one component to another and that's the main idea of why state management like Vuex is a better solution because it provides a centralized state manage which you can access from any component

Upvotes: 0

Related Questions