【源码解析】vue-create-api作者黄轶

【源码解析】vue-create-api作者黄轶vue create api 是干嘛的 在 README md 中这样介绍的 一个能够让 Vue 组件通过 API 方式调用的插件 vue create api 源码地址 安装使用 目前提供两种安装 通过 npm install vue create api 或者引入 js 静态资源文件 在 README md 中提供了使用示例 如下 import

大家好,我是讯享网,很高兴认识大家。

在 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 工具库
接下来我们会从 入口 开始分析,深入了解它的原理及实现过程。

import { camelize, escapeReg, isBoolean } from ‘./util’
import { assert, warn } from ‘./debug’
import apiCreator from ‘./creator’
import instantiateComponent from ‘./instantiate’

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. createVue.prototype[createName]apithis.createDialog() 和 Dialog.$create() 的实现过程。

processComponentName 方法非常简单,代码如下:

f

小讯
上一篇 2025-03-25 11:33
下一篇 2025-03-19 10:03

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/36156.html