问题描述:
在 main.js 文件中,通过 Vue.prototype 和 Vue.use() 两种方式注册插件有什么不同呢?
每一个Vue组件都是Vue的实例,所以组件内this可以拿到Vue.prototype上添加的属性和方法。
Vue.use() 相当于使用一个中间件,用于注册第三方库。
// 在组件中,通过 this.$post 来使用方法
import request from 'utils/request'
Vue.prototype.$post = request.post
import Antd from 'ant-design-vue'
import db from 'utils/localstorage'
Vue.use(Antd)
Vue.use({
install (Vue) {
Vue.prototype.$db = db
}
})
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
首先,不管你采用哪种方式,最终实现的调用方式都是
vm.api()
也就是说,两种方法,实现的原理都是在Vue.prototype
上添加了一个方法。所以结论是“没有区别”。
再来说说Vue.use()
到底干了什么。
我们知道,Vue.use()
可以让我们安装一个自定义的Vue插件。为此,我们需要声明一个install函数
// 创建一个简单的插件 say.js
var install = function(Vue) {
if (install.installed) return // 如果已经注册过了,就跳过
install.installed = true
Object.defineProperties(Vue.prototype, {
$say: {
value: function() {console.log('I am a plugin')}
}
})
}
module.exports = install
然后我们要注册这个插件
import say from './say.js'
import Vue from 'vue'
Vue.use(say)
这样,在每个Vue的实例里我们都能调用say
方法了。
我们来看Vue.use
方法内部是怎么实现的
Vue.use = function (plugin) {
if (plugin.installed) {
return;
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else {
plugin.apply(null, args);
}
plugin.installed = true;
return this;
};
其实也就是调用了这个install
方法而已。