How to create global functions in vue js
One way to go about it is by using the Vue mixins. Another great way to go about that is by using Plugin.
Notice how I declared them and the difference between how I called the two global variables, especially the dollar sign($) in the plugin option. Both
this.gMixinFun()
andthis.$gPluginFun()
will be available as global method in the Vue instance Options.
OPTION 1: Using Mixin
1 2 3 4 5 6 7 |
Vue.mixin({ methods: { gMixinFun: function() { return "this is a mixin test" } } }); |
how to use in components?
1 2 3 4 |
//called in component this.gMixinFun(); //console output console.log("Using mixins =>", this.gMixinFun()); |
OPTION 2: Using plugin
1 2 3 4 5 6 7 8 |
const plugin = { install() { Vue.gPluginFun = () => 'this is a plugin test' //Vue.gPluginFun() Vue.prototype.$gPluginFun = () => 'this is a plugin test' //this.$gPluginFun() } } Vue.use(plugin) |
how to use in components?
1 2 3 4 5 6 7 8 |
//use with Vue Vue.gPluginFun(); //or use with this this.gPluginFun(); //use with Vue Vue.$gPluginFun(); //or use with this this.$gPluginFun(); |
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes0
No0