前言
- 什么是Vue.use()
- Vue.use的简单使用
- 为什么在引入Vue-Router、ElementUI的时候需要Vue.use(),而引入axios的时候,不需要Vue.use()
- Vue-Router、ElementUI在Vue.use()分别做了什么
- Vue.use原理
- 如何编写一个Vue插件?
什么是Vue.use(plugin)
Vue.use是用来安装插件的。
用法
Vue.use(plugin)
- 如果插件是一个对象,必须提供 install 方法。
- 如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。
- Vue.use(plugin)调用之后,插件的install方法就会默认接受到一个参数,这个参数就是Vue。
该方法需要在调用 new Vue() 之前被调用,主要都是因为安装组件时,组件给Vue添加全局功能,所以必须写在new Vue() 之前,否则创建的Vue实例无法获取插件添加的Vue全局功能。
当 install 方法被同一个插件多次调用,插件将只会被安装一次。
小结
- Vue.use是官方提供给开发者的一个api,用来注册、安装Vuex、vue-router、ElementUI之类的插件。
- install 函数接受2个参数:第一个Vue构造函数,第二个是选项对象。
- 当 install 方法被同一个插件多次调用,插件将只会被安装一次。
Vue.use的简单使用
使用
我们在用Vue-cli初始化项目的时候,会生成一个入口文件main.js,在main.js中,如果我们安装了Vue-Router、Vuex、ElementUI,并且想要在项目中使用,就得在入口文件main.js中调用一下Vue.use()
Vue.use(Router);
Vue.use(Vuex);
Vue.use(ElementUI);
这样就算是完成了对三个插件的安装,我们可以在组件中调用 this. r o u t e r 、 t h i s . router、this. router、this.route、this. s t o r e 、 t h i s . store、this. store、this.message()等方法。
思考
为什么在引入Vue-Router、Vuex、ElementUI的时候需要Vue.use()?而引入axios的时候,不需要Vue.use()?
我们在讲什么是Vue.use的时候已经说了,要用use安装的插件,要么是一个对象,对象里包含install方法;要么本身就是一个方法(自身就是install方法)。
看到这里你一定会疑惑:
- 同样是插件,为什么有些插件要有install方法才能正常运行(如VueRouter),有一些却可以没有install方法也可以使用(如axios)?
- 插件的install方法,可以为我们做什么?
Vue-Router、ElementUI在install里面到底做了什么?
在探究这个问题之前,我们先看看Vue.use这个方法到底做了什么。
Vue中的use原理
src/core/global-api/use.js
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
// 获取已经安装的插件
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
// 看看插件是否已经安装,如果已经安装过了,直接返回
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters:获取Vue.use(plugin,xx,xx)中的其他参数。
// 比如 Vue.use(plugin, {size:'mini', theme:'black'}),就会回去到plugin意外的参数
const args = toArray(arguments, 1)
// 在参数的第一位插Vue,从而保证第一个参数Vue实例
args.unshift(this)
// 插件要么是一个函数,要么是一个对象(对象包含install方法)
if (typeof plugin.install === 'function') {
// 调用插件的install方法,并传入Vue实例
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
// 在已经安装的插件数组中,放入刚刚安装的插件
installedPlugins.push(plugin)
return this
}
}
Vue.use方法主要做了如下的事:
- 检查插件是否安装,如果安装了就不再安装
- 如果没有没有安装,那么调用插件的install方法,并传入Vue实例
我们知道了Vue.use做了什么之后。我们看看那些我们常见的插件,是如何利用这个use方法的。
Element中的install
src/index.js
const install = function(Vue, opts = {}) {
locale.use(opts.locale);
locale.i18n(opts.i18n);
// components是ElementUI的组件数组,里面有Dialog、Input之类的组件
components.forEach(component => {
// 往Vue上面挂载组件
Vue.component(component.name, component);
});
Vue.use(InfiniteScroll);
Vue.use(Loading.directive);
// 自定义一些参数
Vue.prototype.$ELEMENT = {
size: opts.size || '',
zIndex: opts.zIndex || 2000
};
// 在Vue原型上注册一些方法,这就是为什么我们可以直接使用this.$alert、this.$loading的原因,值就是这么来的。
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;
Vue.prototype.$bsPopoverMenu = PopoverMenu;
};
bs-ui-pro全局配置
在引入 BSUI 时,可以传入一个全局配置对象。该对象目前支持 size 与 zIndex 字段。size 用于改变组件的默认尺寸,zIndex 设置弹框的初始 z-index(默认值:2000)。按照引入 BSUI 的方式,具体操作如下:
import Vue from 'vue';
import BSUI from 'bs-ui-pro';
Vue.use(BSUI, { size: 'small', zIndex: 3000 });
按照以上设置,项目中所有拥有 size 属性的组件的默认尺寸均为 ‘small’,弹框的初始 z-index 为 3000。
同样的方法,我们来看看Vue-Router的install又做了什么。
Vue-Router中的install
src/install.js
import View from './components/view'
import Link from './components/link'
export let _Vue
export function install (Vue) {
if (install.installed && _Vue === Vue) return
install.installed = true
_Vue = Vue
const isDef = v => v !== undefined
const registerInstance = (vm, callVal) => {
let i = vm.$options._parentVnode
if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
i(vm, callVal)
}
}
Vue.mixin({
beforeCreate () {
// 如果改该组件是根组件
if (isDef(this.$options.router)) {
// 设置根组件叫_routerRoot
this._routerRoot = this
// $options是在main.js里,new Vue里的参数,根组件的_router属性为new Vue传进来的router
this._router = this.$options.router
this._router.init(this)
// 把this._router.history.current变成响应式,底层是 Object.defineProperty
Vue.util.defineReactive(this, '_route', this._router.history.current)
} else {
// 如果该组件不是根组件,那么递归往上找,直到找到根组件
// 因为Vue渲染组件是先渲染根组件,然后渲染根组件的子组件、孙子组件
// 结果就是每一个组件都有this._routerRoot属性,该属性指向了根组件
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
}
registerInstance(this, this)
},
destroyed () {
registerInstance(this)
}
})
// 把自身的$router代理为this._routerRoot(根组件)的_router
// 根组件的_router就是new Vue传入的rouer
// 这样就实现了每个vue组件都有$router属性
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
// 同理,这样就是把自身的$route,代理到根组件传入的route
Object.defineProperty(Vue.prototype, '$route', {
get () { return this._routerRoot._route }
})
// 注册 <router-view>组件
Vue.component('RouterView', View)
// 注册<router-link>组件
Vue.component('RouterLink', Link)
const strats = Vue.config.optionMergeStrategies
// use the same hook merging strategy for route hooks
strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created
}
vue-router的install方法主要帮我们做了如下事情:
- 通过minxi混入的方式,如果自身是根组件,就把根组件的_router属性映射为new Vue传入的router实例(this.$options.router)。
- 如果自身不是根组件,那么层层往上找,直到找到根组件,并用_routerRoot标记出根组件
- 为每一个组件代理 r o u t e r 、 router、 router、route属性,这样每一个组件都可以取到 r o u t e r 、 router、 router、route
- 注册、组件
小结
看到这里,你应该明白了,为什么elementUI、vueRouter需要install才能使用了:两者都需要在install方法,对Vue实例做一些自定义化的操作:比如在vue.prototype中添 m e s s a g e 、 message、 message、loading、 r o u t e r 、 router、 router、route属性、注册组件
为什么axios不需要安装,可以开箱即用?
其实理由也很简单,跟上面需要install的相反的。因为axios是基于Promise封装的库,是完全独立于Vue的,根本不需要挂载在Vue上也能实现发送请求。
而因为VueRouter需要为我们提供
r
o
u
t
e
r
、
router、
router、routers之类的属性,要依赖与Vue或者操作Vue实例才能实现。
Vue.use实际上就是Vue实例与插件的一座桥梁
看下BsHeader例子
使用:main.ts
import { BsHeader } from 'bs-ui-pro';
Vue.use(BsHeader);
BsHeader的install:packages-bs/header/index.js
import BsHeader from './src/main';
/* istanbul ignore next */
BsHeader.install = function(Vue) {
Vue.component(BsHeader.name, BsHeader);
};
export default BsHeader;
packages-bs/header/src/main.vue
<template>
<div class="bs-header-outer">
<div
class="bs-header"
:class="[
fixed ? 'bs-header--fixed' : '',
isOpen ? 'bs-header--close' : 'bs-header--open'
]"
>
<div class="bs-header-left">
<span class="bs-header__icon">
<i
:class="isOpen ? 'bs-icon-caidanshouqi' : 'bs-icon-caidanzhankai'"
@click="toogleMenu"
></i>
</span>
</div>
<div class="bs-header-right">
<slot name="extension"></slot>
<span v-if="userInfoList" class="bs-header__icon">
<el-dropdown
size="medium"
class="bs-header__dropdown"
@command="userClick"
>
<div class="bs-header-user__box">
<i class="bs-icon-gerenzhongxin"></i>
<span class="bs-header-user">{{ username }}</span>
<i class="bs-header-down bs-icon-xialajiantou"></i>
</div>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item
v-for="userInfo in userInfoList || userInfoArray"
:key="userInfo.key"
:command="userInfo.key"
>{{ userInfo.value }}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</span>
<span v-if="showHelp" class="bs-header__icon">
<el-dropdown
size="medium"
class="bs-header__dropdown"
@command="helpClick"
>
<i class="bs-icon-wenti"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item
v-for="help in helpList || helpArray"
:key="help.key"
:command="help.key"
>{{ help.value }}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</span>
<span class="bs-header__icon">
<el-dropdown
size="medium"
class="bs-header__dropdown"
@command="helpClick"
>
<i
class="bs-screen-icon"
:class="isFullScreen ? 'bs-icon-shousuo' : 'bs-icon-quanping'"
@click="toogleFullScreen"
></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item
:key="
isFullScreen
? t('bsEl.header.exitFullScreen')
: t('bsEl.header.fullScreen')
"
:command="
isFullScreen
? t('bsEl.header.exitFullScreen')
: t('bsEl.header.fullScreen')
"
>{{
isFullScreen
? t('bsEl.header.exitFullScreen')
: t('bsEl.header.fullScreen')
}}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</span>
</div>
</div>
<div v-if="fixed" class="bs-header-empty-box"></div>
</div>
</template>
<script>
import Service from './service';
import Locale from 'element-ui/src/mixins/locale';
export default {
name: 'BsHeader',
mixins: [Locale],
props: {
collapse: {
type: Boolean,
default: false // 展开
},
fixed: {
type: Boolean,
default: true
},
showHelp: {
type: Boolean,
default: true
},
username: {
type: String,
default: 'admin'
},
userInfoList: {
type: [Array, Boolean]
},
helpList: {
type: Array
}
},
data() {
return {
isOpen: true,
isFullScreen: false,
service: new Service(),
userInfoArray: [
{ key: 'userCenter', value: this.t('bsEl.header.userCenter') },
{ key: 'logout', value: this.t('bsEl.header.logout') }
],
helpArray: [
{ key: 'doc', value: this.t('bsEl.header.helpDoc') },
{ key: 'about', value: this.t('bsEl.header.about') }
]
};
},
methods: {
toogleMenu() {
this.isOpen = !this.isOpen;
this.$emit('toogle-menu', this.isOpen);
},
userClick(value) {
this.$emit('user-click', value);
},
helpClick(value) {
this.$emit('help-click', value);
},
toogleFullScreen() {
this.isFullScreen = !this.isFullScreen;
this.isFullScreen ? this.service.fullScreen() : this.service.exitScreen();
this.$emit('toogle-full-screen', this.isFullScreen);
}
},
created() {
this.isOpen = this.collapse;
}
};
</script>