浅谈vue.use()方法从源码到使用

2020-06-16 05:56:50易采站长站整理

if (installedPlugins.indexOf(plugin) > -1) {
return this
}
const args = toArray(arguments, 1)
args.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}

上面源码中使用了工具函数 toArray ,该函数定义在 src/shared/util.js


export function toArray (list: any, start?: number): Array<any> {
start = start || 0
let i = list.length - start
const ret: Array<any> = new Array(i)
while (i--) {
ret[i] = list[i + start] }
return ret
}

了解一下源码实现了什么逻辑

Vue.use = function (plugin: Function | Object) {

在全局api Vue 上定义了 use 方法,接收一个 plugin 参数可以是 Function 也可以是 Object,这就和前面官方规定的 Vue.use() 第一个参数要求的类型对应上了。

if (installedPlugins.indexOf(plugin) > -1) {

用来判断该插件是不是已经注册过,防止重复注册。

const args = toArray(arguments, 1)

arguments是 Vue.use() 方法的参数列表是一个类数组,后面的 1 先理解成一个常量,toArray 方法的作用就是把第一个 Array 参数从下标为1截取到最后。也就拿到了 Vue.use() 方法除去第一个之外的其他参数,这些参数准备在调用 instll 方法的时候传入。

if (typeof plugin.install === 'function') {
} else if (typeof plugin === 'function') {

这里的if语句是判断 Vue.use() 传入的第一个参数是 Object 还是 Function。

plugin.install.apply(plugin, args)
plugin.apply(null, args)

判断完之后执行那个对应的 install 方法,用 apply 改变 this 指向,并把 toArray 得到的剩余参数传入。

installedPlugins.push(plugin)

最后记录该组件已经注册过了

现在我们发现 Vue.use() 的注册本质上就是执行了一个 install 方法,install 里的内容由开发者自己定义,通俗讲就是一个钩子可能更贴近语义化而已。

Vue.use()有什么用

在 install 里我们可以拿到 Vue 那么和 Vue 相关的周边工作都可以考虑放在 Vue.use() 方法里,比如:

directive注册
mixin注册
filters注册
components注册
prototype挂载

echarts 用 Vue.use() 来注册

main.js


import Vue from 'vue'
import echarts from './echarts.js'