vue-create-api 是干嘛的?
在 README.md 中这样介绍的,一个能够让 Vue 组件通过 API 方式调用的插件。( vue-create-api 源码地址 )
安装使用
目前提供两种安装,通过 npm install vue-create-api, 或者引入js静态资源文件。
在 README.md 中提供了使用示例,如下:
import CreateAPI from ‘vue-create-api’
Vue.use(CreateAPI)
Vue.use(CreateAPI, {
componentPrefix: ‘cube-’
apiPrefix: ‘$create-’
})
import Dialog from ‘./components/dialog.vue’
Vue.createAPI(Dialog, true)
Dialog.$create({
$props: {
title: ‘Hello’,
content: ‘I am from pure JS’
}
}).show()
this.$createDialog({
$props: {
title: ‘Hello’,
content: ‘I am from a vue component’
}
}).show()
复制代码
引入 vue-create-api 插件,安装插件时,可以设置 componentPrefix 和 apiPrefix 两个参数,这里会在 Vue 构造器下添加一个 createAPI 方法。引入 Dialog 组件,调用 createAPI 生产对应 API,并挂载到 Vue.prototype 和 Dialog 对象上。之后可以在 vue 组件中通过 this 调用,或者在 js 文件中 $create 创建并使用。
目录
文件名称 说明
creator 创建组件
debug 错误提示
index 主入口
instantiate 实例化
parse 参数设置
util 工具库
接下来我们会从 入口 开始分析,深入了解它的原理及实现过程。
入口
如果 Vue 插件是一个对象,必须提供 install 方法。如果插件是一个函数,该函数会被作为 install 方法。 install 方法调用时,会将 Vue 作为参数传入。 vue-create-api 的 install 方法在 src/index.js 文件中定义:
import { camelize, escapeReg, isBoolean } from ‘./util’
import { assert, warn } from ‘./debug’
import apiCreator from ‘./creator’
import instantiateComponent from ‘./instantiate’
function install(Vue, options = {}) {
const {componentPrefix = ‘’, apiPrefix = ‘$create-’} = options
Vue.createAPI = function (Component, events, single) {
if (isBoolean(events)) {
single = events
events = []
}
const api = apiCreator.call(this, Component, events, single)
const createName = processComponentName(Component, {
componentPrefix,
apiPrefix,
})
Vue.prototype[createName] = Component.$create = api.create
return api
}
}
复制代码
install 方法提供 options 配置参数, componentPrefix 为组件名前缀,最终生成的 API 会忽略该前缀, apiPrefix 为生成的 API 统一添加前缀,默认为 $create。
在方法体内定义了 Vue.createAPI 方法,并提供三个参数 Component 组件、 events 事件数组、 single 是否采用单例模式实例化组件。 events 可以传 Boolean 类型或者 Array 类型值。 示例中 events 为 true ,根据代码逻辑,当 events 为 Boolean 类型时, single = events 所以 single 为 true ,events 赋值为 []。
通过 apiCreator 方法获得 api 对象,内部有 before 和 create 两个方法。 这里之所以用到 call,其作用就是要将 this 指向 Vue 类。代码文件路径在 src/creator.js ,这部分实现逻辑之后会细讲,我们接着往下看。
通过 processComponentName 方法获得 crateName 属性名,将 api.create 赋给 Component. c r e a t e 和 V u e . p r o t o t y p e [ c r e a t e N a m e ] , 最 后 返 回 a p i 。 这 里 也 就 是 上 面 示 例 中 t h i s . create 和 Vue.prototype[createName],最后返回 api。这里也就是上面示例中 this. create和Vue.prototype[createName],最后返回api。这里也就是上面示例中this.createDialog() 和 Dialog.$create() 的实现过程。
processComponentName 方法非常简单,代码如下:
f