插件的功能主要有以下几种:
添加全局方法或者
property
。如:vue-custom-element
添加全局资源:指令/过滤器/过渡等。如
vue-touch
通过全局混入来添加一些组件选项。如
vue-router
添加
Vue
实例方法,通过把它们添加到Vue.prototype
上实现。一个库,提供自己的
API
,同时提供上面提到的一个或多个功能。如vue-router
通过全局方法 Vue.use()
使用插件。它需要在你调用 new Vue()
启动应用之前完成:
js
// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
new Vue({
// ...组件选项
})
Vue.use
源码:
js
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
}