注: 所有通过 createAPI 实现的通过 API 的形式调用的自定义组件(cube-ui 内置的组件)都需要通过 Vue.use 注册才可以。

  • 用法:

    • 该方法在 Vue 的 prototype 上增加一个名为 $create{camelize(Component.name)} 的方法,这样就可以在其他组件中直接通过 const instance = this.$createAaBb(config, [renderFn, single]) 这样来实例化组件了,而且这个实例化组件的元素是被附加到 body 元素下的。

    • const instance = this.$createAaBb(config, renderFn, single)

参数:

配置参数 config:

1.8.0 版本后 config 中可以直接设置 $props 和 $events,$props 中的值是响应式的,自动监控当前实例化上下文(即 this.$createXx 中的 this)的上对应的属性值:

create-api - 图2

$props 示例,约定结构 { [key]: [propKey] }:

title、content、open 就是传递给组件的 Prop 的 key,而对应 Prop 的值则按照如下规则获取:

  1. - 如果是非字符串,则直接取配置的 propKey 作为值
  2. - 如果是字符串,且配置的 propKey 不在当前实例上下文属性上,则直接取 propKey 作为值
  3. - 是字符串,且在当前实例上下文属性上,那么直接获取当前实例上下文对应的 propKey 的值,且会监控这个值的变化实时更新到组件实例上

$events 示例,约定结构 { [eventName]: [eventValue] }:

  1. {
  2. click: 'clickHandler',
  3. select: this.selectHandler
  4. }

click、select 就是事件名,而对应的事件回调则按照如下规则获取:

1.10.0 版本以后 config 中可以设置 Vue 支持的所有的,但是必须要加 $,例如:

  1. this.$createAaBb({
  2. $attrs: {
  3. id: 'id'
  4. },
  5. $class: {
  6. 'my-class': true
  7. }

返回值 instance:

这个实例会被附加或代理 remove 方法

如果调用了,该实例就会被销毁且会从 body 下移除。

如果说实例化上下文(即 this.$createXx 中的 this)销毁的话会自动移除销毁该实例元素。

  • 示例:

我们先编写一个 Hello.vue 组件:

  1. <template>
  2. <div @click="clickHandler">
  3. {{content}}
  4. <slot name="other"></slot>
  5. </div>
  6. </template>
  7. export default {
  8. name: 'hello',
  9. props: {
  10. content: {
  11. type: String,
  12. default: 'Hello'
  13. }
  14. },
  15. methods: {
  16. clickHandler(e) {
  17. this.$emit('click', e)
  18. }
  19. }
  20. </script>

然后我们再通过 createAPI 把 Hello.vue 变成一个 API 式调用的组件并调用。

示例中就是创建了一个需要 API 调用的组件 Hello,然后在其他组件中去使用,重点就是 showHello() 方法做的事情:调用 this.$createHello(config, renderFn) 实现组件的实例化。

如何在普通 js 文件中或者全局调用

一般当你在 Vue 实例中,你可以直接通过 this.$createHello(config, renderFn) 调用该组件。而如果在普通 JS 中this不是 Vue 实例,这时就可以通过组件本身的 $create 来进行实例化了,比如:

  1. import Hello from './Hello.vue'
  2. import {
  3. createAPI
  4. } from 'cube-ui'
  5. // 创建 this.$createHello and $Hello.create API
  6. createAPI(Vue, Hello, ['click'], true)
  7. Hello.$create(config, renderFn)

或者内置的组件,例如 Dialog:

  1. import Vue from 'vue'
  2. import { Dialog } from 'cube-ui'
  3. Vue.use(Dialog)
  4. Dialog.$create({
  5. ...
  6. })