常见的用法有Vue.use(VueRouter); Vue.use(ElementUI)
先看看 vue的源码
function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
//插件只能注册一次,注册后不再注册 if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1);
// 参数添加vue示例,在install函数使用 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 }; }
可以写个简单的插件
Vue.use({ install:function(vue){ vue.component('comp',{
name: 'comp', template: `<div>插件demo</div>` }) } })