Vue.use 与 Vue.prototype 的区别

本人对Vue的原型prototype有了解过,知道这是啥玩意,但对于Vue.use只知会用,却不知其意。今天来看看。

示例

// 引入公共方法扩展
import common from '@/prototypeEx/common.js'
Vue.prototype.common = common
// 引入公共缓存方法
import cacheEx from '@/prototypeEx/cacheEx.js'
Vue.prototype.cacheEx = cacheEx
// 引入大数据展示 插件
const echarts = require('echarts')
Vue.prototype.$echarts = echarts

import uploader from 'vue-simple-uploader'
Vue.use(uploader)
// 引人自己封装的全局注册的公共组件
import ztable from '@/components/index.js'
Vue.use(ztable)

解答(本人看完豁然开朗)

Vue.useVue.prototype没有本质区别,Vue.use就是在Vue.prototype基础上又封装了一层而已,他们实现的原理都是在Vue.prototype上添加了一个方法,Vue.prototype适合于注册Vue生态外的插件,Vue.use适合于注册Vue生态内的插件。

分析过程

1.$echarts变量前加上$,是防止被组件中的变量意外覆盖。

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;
}

总结

看了源码才知道原来`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`进一步的封装了一次。

猜你喜欢

转载自blog.csdn.net/u012174809/article/details/123394249
今日推荐