Understanding Vue.use() for Plugin Installation
Plugins that need to be installed via Vue.use() must expose an install method. This method allows you to attach global capabilities to the Vue framework.
Global Capabilities You Can Add
- Global methods or properties attached directly to the Vue constructor
- Global resources such as directives, filters, or transitions
- Component options via global mixins
- Instance methods by attaching them to
Vue.prototype - Complete libraries providing their own API combined with one or more of the above
How Vue.use() Works
/* @flow */
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
const registeredPlugins = (this._registeredPlugins || (this._registeredPlugins = []))
if (registeredPlugins.indexOf(plugin) > -1) {
return this
}
const params = toArray(arguments, 1)
params.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, params)
} else if (typeof plugin === 'function') {
plugin.apply(null, params)
}
registeredPlugins.push(plugin)
return this
}
}
Execution Flow
Step 1: Duplicate Preveniton
Check if the plugin already exists in this._registeredPlugins. If it does, return immediately to prevent duplicate installations.
Step 2: Argument Collection
Extract all arguments passed to use() except the first one (the plugin itself). This enables passing additional configuration options like Vue.use(MyPlugin, { option: value }).
Step 3: Context Binding Prepend the current Vue instance as the first element in the arguments array. This ensures the plugin has access to Vue's context.
Step 4: Execution
If the plugin has an install function, invoke it with the prepared arguments. Otherwise, if the plugin itself is a function, call it directly with the arguments.
Step 5: Registration
Add the plugin to this._registeredPlugins to track it for duplicate prevention.
Plugin Structure Example
const MyPlugin = {}
MyPlugin.install = function (Vue, config) {
// 1. Global methods or properties
Vue.calculateTotal = function (items) {
// logic...
}
// 2. Global directives
Vue.directive('highlight', {
bind (element, binding, vnode, oldVnode) {
// logic...
}
})
// 3. Mixins for component options
Vue.mixin({
created: function () {
// logic...
}
})
// 4. Instance methods
Vue.prototype.$processData = function (options) {
// logic...
}
}
The plugin pattern follows a consistent structure where the install function receives Vue as its first paramteer, followed by any additional options passed during registration.