01 参数
{Object | Function} plugin
02 用法
安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。
该方法需要在调用 new Vue() 之前被调用。
当 install 方法被同一个插件多次调用,插件将只会被安装一次。
03 参考
MyPlugin.install = function (Vue, options) {// 1. 添加全局方法或 propertyVue.myGlobalMethod = function () {// 逻辑...}// 2. 添加全局资源Vue.directive('my-directive', {bind (el, binding, vnode, oldVnode) {// 逻辑...}...})// 3. 注入组件选项Vue.mixin({created: function () {// 逻辑...}...})// 4. 添加实例方法Vue.prototype.$myMethod = function (methodOptions) {// 逻辑...}}
04 源码
我们可以从源码入手分析一下,基于vue 2.6.11 版本,源码地址为:src/core/global-api/use.js
export function initUse (Vue: GlobalAPI) {// 接受一个plugin参数,限制为 Function | Object两种类型Vue.use = function (plugin: Function | Object) {// _installedPlugins 存储所有注册过的 pluginconst installedPlugins = (this._installedPlugins || (this._installedPlugins = []))// 保存注册组件的数组,不存在则创建,存在则直接返回,不允许重复注册if (installedPlugins.indexOf(plugin) > -1) {return this}// additional parameters// 将传入的参数转换成数组const args = toArray(arguments, 1)// 将Vue对象拼接到数组头部args.unshift(this)// 如果提供了 install 方法,则直接调用if (typeof plugin.install === 'function') {// 如果组件是对象,且提供install方法,调用install方法将参数数组传入,改变`this`指针为该组件plugin.install.apply(plugin, args)} else if (typeof plugin === 'function') {// 否则直接执行plugin.apply(null, args)}// 将plugin存储到 installedPlugins,表示y已经注册过installedPlugins.push(plugin)return this}}/*** Convert an Array-like object to a real Array.*/export function toArray (list: any, start?: number): Array<any> {start = start || 0let i = list.length - startconst ret: Array<any> = new Array(i)while (i--) {ret[i] = list[i + start]}return ret}
基于 vue-router3.1.6 版本,源码位置: src/install.js
import View from './components/view'import Link from './components/link'/*export 一个 Vue 引用,在打包的时候不希望把 Vue作为依赖包打进去,但是又希望可以使用 Vue提供的一些方法,*/export let _Vue// Vue.use安装插件时候需要暴露的install方法export function install (Vue) {// 判断是否已安装过if (install.installed && _Vue === Vue) returninstall.installed = true_Vue = Vueconst isDef = v => v !== undefinedconst registerInstance = (vm, callVal) => {let i = vm.$options._parentVnodeif (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {i(vm, callVal)}}// 混入 beforeCreateVue.mixin({beforeCreate () {// 在option上面存在router则代表是根组件if (isDef(this.$options.router)) {this._routerRoot = this// 根组件的_router属性为,new Vue传进去的routerthis._router = this.$options.router// 执行 init方法this._router.init(this)// 通过defineReactive方法,来把this._router.history.current变成响应式的,这个方法的底层就是object.definePropertyVue.util.defineReactive(this, '_route', this._router.history.current)} else {// 如果该组件不是根组件,那么递归往上找,直到找到根组件的。this._routerRoot = (this.$parent && this.$parent._routerRoot) || this}registerInstance(this, this)},destroyed () {registerInstance(this)}})/*下面通过给 Vue.prototype定义$router、$route属性后,所有的Vue实例(组件)都可以直接访问到*/// 设置代理,访问 this.$router 时直接代理到 this._routerRoot._routerObject.defineProperty(Vue.prototype, '$router', {get () { return this._routerRoot._router }})// 设置代理,访问 this.$route 时直接代理到 this._routerRoot._routeObject.defineProperty(Vue.prototype, '$route', {get () { return this._routerRoot._route }})// 注册 router-view 和 router-link 组件Vue.component('RouterView', View)Vue.component('RouterLink', Link)const strats = Vue.config.optionMergeStrategies// use the same hook merging strategy for route hooksstrats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created}// 组件的注册const install = function(Vue, opts = {}) {locale.use(opts.locale);locale.i18n(opts.i18n);components.forEach(component => {Vue.component(component.name, component);});Vue.use(InfiniteScroll);Vue.use(Loading.directive);Vue.prototype.$ELEMENT = {size: opts.size || '',zIndex: opts.zIndex || 2000};Vue.prototype.$loading = Loading.service;Vue.prototype.$msgbox = MessageBox;Vue.prototype.$alert = MessageBox.alert;Vue.prototype.$confirm = MessageBox.confirm;Vue.prototype.$prompt = MessageBox.prompt;Vue.prototype.$notify = Notification;Vue.prototype.$message = Message;};/* istanbul ignore if */if (typeof window !== 'undefined' && window.Vue) {install(window.Vue);}
vue-router中的install方法主要做了以下几件事:
- 通过
mixin混入的方式,如果是根组件,则直接把根组件的_router设置为this.$options.router - 如果不是根组件,那么递归往上找,直到找到根组件的,使用
_routerRoot标记 - 通过给
Vue.prototype定义$router、$route属性后,使得所有的Vue实例(组件)都可以直接访问到$router、$route属性 - 注册
<router-link>、<router-view>组件
