「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战」
引子
import Vue from 'vue'
import Element from 'element-ui'
Vue.use(Element)
import echarts from 'echarts'
vue.prototype.$echarts = echarts
这样的代码我们肯定很熟悉, 但是对于Vue.use和Vue.prototype的区别是什么,可能还不一定完全清楚。Vue为什么要提高两个注册插件的方式?他们各自有什么优点和联系?先说结论,Vue.use和Vue.prototype没有本质区别,Vue.use就是在Vue.prototype基础上又封装了一层而已,他们实现的原理都是在Vue.prototype上添加了一个方法,Vue.prototype适合于注册Vue生态外的插件,Vue.use适合于注册Vue生态内的插件。
Vue.prototype的用法
如果需要设置全局变量,在main.js中,Vue实例化的代码里添加。 不想污染全局作用域。这种情况下,你可以通过在 原型 上定义它们使其在每个Vue实例中可用。
vue.prototype.$echarts = echarts
这样$echarts就在所有Vue实例中可用了,变量前加上$,是防止被组件中的变量意外覆盖。
Vue.use()的 用法
- 通过全局方法 Vue.use() 使用插件
- Vue.use 会自动阻止多次注册相同插件
- 它需要在你调用 new Vue() 启动应用之前完成
- Vue.use() 方法至少传入一个参数,该参数类型必须是 Object 或 Function,如果是 Object 那么这个 Object 需要定义一个 install 方法,如果是 Function 那么这个函数就被当做 install 方法。在 Vue.use() 执行时 install 会默认执行,当 install 执行时第一个参数就是 Vue,其他参数是 Vue.use() 执行时传入的其他参数。
import Vue from 'vue'
import Element from 'element-ui'
Vue.use(Element)
两种方法的本质
下面先来看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方法内容, 我们居然看到了Vue.prototype.$toast = toast;,
// 准备好 install 方法 给 Vue.use() 使用
const install = function (Vue) {
if (install.installed) return;
install.installed = true;
// 将包装好的 toast 挂到Vue的原型上,作为 Vue 实例上的方法
Vue.prototype.$toast = toast;
}
// 默认导出 install
export default {
install,
};
看了源码才知道原来Vue.use主要是执行install方法,而install主要也是执行Vue.prototype方法。所以,其实Vue.use()方法的核心就是Vue.prototype,只不过又封装了一层,更加的灵活,扩展性更好。
总结
把vue理解成一棵树,Vue.use和Vue.prototype都是在这颗树上挂载插件的方式,不同之处是使用vue.prototype,插件不需要实现install方法,简单粗暴,拿来就用,但是灵活性不如Vue.use(), 而Vue.use(),却要求插件必须实现instal方法或者该插件本身就是函数,在install方法可以完成自己的逻辑, 所以Vue.use()的方式更加的强大,灵活,扩展性更好。但是两者并没有高低之分, 只是有着各自的应用场景,Vue.prototype适合于非Vue生态的插件,而Vue.use()适合于Vue生态内的插件,如echarts,两者互相配合,一个简单实用,一个灵活扩展性好。而且,Vue.use的实现依赖于Vue.prototype,最本质的理解就是Vue.use包裹着Vue.prototype进一步的封装了一次。