Four Methods to Define Global Functions in Vue.js
The article outlines four practical ways to create global functions in Vue—mounting on Vue.prototype, using Vue.use with a plugin, applying a global mixin, and leveraging the $root event bus—while noting each method's advantages and limitations.
Vue developers often need a way to expose utility functions across all components. This guide presents four distinct techniques for defining global functions in Vue.js.
1. Mount to Vue.prototype
Directly assign the function to the prototype, e.g., Vue.prototype.myMethod = function () { /* logic */ };. The function becomes available on every component instance as this.myMethod(), but IDEs provide no autocomplete hint.
2. Use Vue.use(plugin)
A plugin must expose an install method whose first argument is the Vue constructor. Inside install you can add global methods, properties, directives, mixins, or component options using Vue.prototype. Example:
function install (Vue, options) {
// 1. add global method or property
Vue.myGlobalMethod = function () { /* logic */ };
// 2. add global directive
Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) { /* logic */ } });
// 3. inject component options
Vue.mixin({ created () { /* logic */ } });
// 4. add instance method
Vue.prototype.$myMethod = function (methodOptions) { /* logic */ };
}Although the plugin itself does not perform the mounting, it ultimately relies on Vue.prototype to expose the functionality.
3. Global mixin
Calling Vue.mixin(mixins) merges the mixin’s methods into every single‑file component. This approach provides autocomplete support because the methods become part of each component’s type definition.
4. $root event bus
By using the root Vue instance as an event hub, you can create, destroy, and invoke global methods:
// create global method
this.$root.$on('test', function () { console.log('test'); });
// destroy global method
this.$root.$off('test');
// invoke global method
this.$root.$emit('test');Each technique has trade‑offs: prototype mounting is simple but lacks tooling support; plugins encapsulate logic but still depend on the prototype; mixins give better IDE hints; and $root provides a lightweight event‑based approach.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Trendsetter
Latest articles, video tutorials, and open-source projects on React, Vue, Angular, Ionic, React Native, Node.js, Mini Programs, and other cutting-edge technologies. A community for sharing and discussing full-stack development trends.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
