Problem statement could be:
- How to make a function globally available in Vuejs across components.
- How to define a function in Vuejs that I can access from any other Vue Component.
- How to define and access a function across component.
So, In Vue there is inbuilt method that you can use to define your methods that you want to access globally. Which means you will able to access those function from any component you want.
Vue has a thing called mixins that you can use to define your global methods. Let’s see how to do this.
So, open you `main.js` file and And right before you root Vue instance define Vue.mixin({}) function this mixin function takes one object as an argument. In which you need to define your method that you want to access globally like this:
Vue.mixin({
methods: {
callTitle() {
return `CodeChit`;
},
},
});
Inside object, just define your custom functions inside that methods object. Once you done, after that you will be able to access those functions inside any component. If you want use inside template section then just define it like {{ callTitle() }} or If you want to use this inside script section use this.callTitle() to access it.
That’s it. Apart from it you can also use Vue prototype if you want like this:
Vue.prototype.$title = () => 'CodeChit';
And then similarly you will be able to access it as this.$title() and {{ $title() }}.
So, I hope this solved you problem, If yes then please don’t forget to hit the like button given below. And do let me know in the comment section if you know any other method.
Thanks for reading, have a lovely day 🙂