携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情
原理
简介
插件通常用来为 Vue 添加全局功能。-Vue官网
我觉得广义上的插件,实际上就是一些可以复用的功能或组件的封装。
首先分析Vue源码:
//src->core->instance->index.js
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
我们可以发现Vue实例最初是一个函数,然后在其上挂载各种属性。作为函数,我们就可以为其直接添加属性,或者向其prototype上添加参数。
Vue的插件通常包括以下几种:
-
添加全局方法或者 property。如:vue-custom-element
注册代码:
function install(Vue) { Vue.customElement = function vueCustomElement(tag, componentDefinition, options = {}) { //... } //... }可以看到,这里是直接向
Vue实例上添加属性方法。使用:
Vue.customElement()另外,这个插件使用了
Web Component这一新的属性,还得找个时间学习一下。它可以在HTML文件中直接使用自定义标签。 -
添加全局资源:指令/组件/过滤器/过渡等。如 vue-touch
注册代码(
vue-touch):vueTouch.install = function (Vue) { Vue.directive('touch', { //... } //... }这里是使用了
Vue的directive定义了一个全局的v-touch指令。<a v-touch:tap="onTap">Tap me!</a> <div v-touch:swipeleft="onSwipeLeft">Swipe me!</div>另外,还可以通过
Vue.filter注册全局的filter来进行使用,比如let plugin = {} plugin.install = function(Vue, options){ Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) }) }则可以直接在
Vue的tempelate中使用<div v-bind:id="rawId | formatId"></div>值得注意的是全局组件的注册,因为很多时候我们开发组件是需要组件样式支撑的。这个时候就需要全局注册组件。比如
element-UI(可惜无了),iview这种组件库就需要注册大量的全局样式。注册代码(部分)(
element-UI):components.forEach(component => { Vue.component(component.name, component); });这里使用
Vue.component注册全局组件,这样注册的组件可以直接在任何组件中引用而不需在script中申明。值得注意的是,这样引入的组件即使未被引用,依然会被打包,因此,在大型组件库中尽量少使用全局注册,否则会增加打包后的js大小。
-
通过全局混入来添加一些组件选项。如 vue-router
注册代码:
export function install (Vue) { Vue.mixin({ beforeCreate () { if (isDef(this.$options.router)) { this._routerRoot = this this._router = this.$options.router this._router.init(this) Vue.util.defineReactive(this, '_route', this._router.history.current) } else { this._routerRoot = (this.$parent && this.$parent._routerRoot) || this } registerInstance(this, this) }, destroyed () { registerInstance(this) } }) }可以看到,这里
vue-router使用了Vue.minin对beforeCreate进行了混入,使该混入钩子在Vue自身的钩子之前调用。 -
添加 Vue 实例方法,通过把它们添加到
Vue.prototype上实现。比如element-UI等组件库。注册代码:
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; }在
Vue的prototype上添加很多参数方法。 -
一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router
vue-router中有一个index.js与install.js,在install.js中,只提供了与Vue相关的注册函数。在index中,定义了很多自己的API。
使用插件
通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成:
// 调用 `DWin.install(Vue)`
Vue.use(DWin)
new Vue({
// ...组件选项
})
也可以传入一个可选的选项对象:
Vue.use(DWin, { someOption: true })
Vue.use 会自动阻止多次注册相同插件,届时即使多次调用也只会注册一次该插件。
Vue.js 官方提供的一些插件 (例如 vue-router) 在检测到 Vue 是可访问的全局变量时会自动调用 Vue.use()。然而在像 CommonJS 这样的模块环境中,你应该始终显式地调用 Vue.use():
// 用 Browserify 或 webpack 提供的 CommonJS 模块环境时
var Vue = require('vue')
var VueRouter = require('vue-router')
// 不要忘了调用此方法
Vue.use(VueRouter)
另外,全局样式表的引入需要直接在main.js中import,这样的css样式也会被全局注册,会影响所有的组件。
开发插件
Vue插件开发其实很简单,最关键的就是其必须要暴露一个install方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:
DWin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
Vue.component('my-component', Mcomponent) //常用
Vue.filter('my-filter', Mfilter)
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
export DWin
应用
根据上面的原理,我们只需要遵循插件定义和使用的规则即可,其目录解构并不重要,但是为了规范,可以新建一个plugin用来存储插件文件,插件的目录解构可以自定义。另外,项目直接使用vue-cli生成一个普通的项目即可。
可以看到,在
index.js文件中,我们定义了install函数,并在Vue的prototype上挂载了一个函数和一个方法,同时,也注册了一个全局的组件dwin。最后将该对象导出。
然后在
main.js中,我们从index.js中引入dw,然后使用Vue.use(dw)将该组件导入。
然后我们就可以在任何组件中使用
dwin组件了。