其实不管使用哪一种方式,最终都是调用方式都是
vue.api()
Vue.use()到底做了些什么,可以使我们安装一个自定义的Vue的插件,为此,我们要声明一个install函数,
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
上面的say是一个简单的插件,然后我们需要注册该插件
import say from './say.js'
import Vue from 'vue'
Vue.use(say)
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;
};
关于JS原型对象prototype
对象我们简单的分成两类,一个是函数对象,一个是普通对象,普通对象是通过函数创建的。
每一个函数对象具有一个prototype属性,而普通对象是没有的。
普通对象的__proto__指向当前函数对象的原型
js通过原型链可以实现继承那么我们可以对Vue.prototype进行操作,对Vue.prototype添加属性或者方法,所有通过new Vue创建的实例都可以继承这些属性或方法,例如我们在main.js 中添加如下代码:
//无关代码省略
Vue.prototype.myName="mmz"
//无关代码省略