注: 所有通过 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)的上对应的属性值:
$props 示例,约定结构 { [key]: [propKey] }:
title、content、open 就是传递给组件的 Prop 的 key,而对应 Prop 的值则按照如下规则获取:
- 如果是非字符串,则直接取配置的 propKey 作为值
- 如果是字符串,且配置的 propKey 不在当前实例上下文属性上,则直接取 propKey 作为值
- 是字符串,且在当前实例上下文属性上,那么直接获取当前实例上下文对应的 propKey 的值,且会监控这个值的变化实时更新到组件实例上
$events 示例,约定结构 { [eventName]: [eventValue] }:
- {
- click: 'clickHandler',
- select: this.selectHandler
- }
click、select 就是事件名,而对应的事件回调则按照如下规则获取:
1.10.0 版本以后 config 中可以设置 Vue 支持的所有的,但是必须要加 $,例如:
- this.$createAaBb({
- $attrs: {
- id: 'id'
- },
- $class: {
- 'my-class': true
- }
返回值 instance:
这个实例会被附加或代理 remove 方法
如果调用了,该实例就会被销毁且会从 body 下移除。
如果说实例化上下文(即 this.$createXx 中的 this)销毁的话会自动移除销毁该实例元素。
- 示例:
我们先编写一个 Hello.vue 组件:
<template>
<div @click="clickHandler">
{{content}}
<slot name="other"></slot>
</div>
</template>
export default {
name: 'hello',
props: {
content: {
type: String,
default: 'Hello'
}
},
methods: {
clickHandler(e) {
this.$emit('click', e)
}
}
</script>
然后我们再通过 createAPI 把 Hello.vue 变成一个 API 式调用的组件并调用。
示例中就是创建了一个需要 API 调用的组件 Hello,然后在其他组件中去使用,重点就是 showHello() 方法做的事情:调用 this.$createHello(config, renderFn) 实现组件的实例化。
如何在普通 js 文件中或者全局调用
一般当你在 Vue 实例中,你可以直接通过 this.$createHello(config, renderFn)
调用该组件。而如果在普通 JS 中this
不是 Vue 实例,这时就可以通过组件本身的 $create
来进行实例化了,比如:
import Hello from './Hello.vue'
import {
createAPI
} from 'cube-ui'
// 创建 this.$createHello and $Hello.create API
createAPI(Vue, Hello, ['click'], true)
Hello.$create(config, renderFn)
或者内置的组件,例如 Dialog:
import Vue from 'vue'
import { Dialog } from 'cube-ui'
Vue.use(Dialog)
Dialog.$create({
...
})