今天看自己项目代码,引入插件包的main.js,留意到引入包或者文件有两种方式:
import Vue from 'vue'
import echarts from 'echarts'
import global from './global.js' //我自己创建的全局变量函数文件
Vue.prototype.$echarts=echarts;
Vue.use(global)
于是就对上述两种方式引入产生了疑问,这两种方式引入有什么区别吗?
通过资料查询,了解到:
1、不是为了vue写的插件(插件内要处理)不支持Vue.use()加载方式
2、非vue官方库不支持new Vue()方式
3、每一个vue组件都是Vue的实例,所以组件内this可以拿到Vue.prototype上添加的属性和方法。
其实我们知道Vue.prototype是在原型上定义,使其在每个Vue中的实例中可用,那么Vue.use()流程是怎么走的?我们可以通过源代码了解其过程:
创建自定义全局函数global.js
// 全局函数
exports.install = function (Vue, options) {
Vue.prototype.alertResult = function (options){//全局函数1
var result;
switch(options){
case 'success':
result='操作成功';
break;
case 'operate fail':
result='操作失败';
break;
case 'invalid data':
result='数据格式错误';
break;
case 'request time out':
result='请求超时';
break;
}
return result;
};
};
过上述引入方式,我们进行引入注册,这样子我们就可以在其他页面使用该全局方法如 this.alertResult (‘success’)
那么,我们可以通过源代码分析,了解Vue.use()实现过程
export function initUse (Vue: GlobalAPI) {
/*https://cn.vuejs.org/v2/api/#Vue-use*/
Vue.use = function (plugin: Function | Object) {
/* istanbul ignore if */
/*标识位检测该插件是否已经被安装*/
if (plugin.installed) {
return
}
// additional parameters
const args = toArray(arguments, 1)
/*a*/
args.unshift(this)
if (typeof plugin.install === 'function') {
/*install执行插件安装*/
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
plugin.installed = true
return this
}
}