Reputation: 1569
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
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
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