简单使用
- 先创建 Hello.vue 组件
<template>
<div>
hello
</div>
</template>
<script>
export default {
name: 'hello',
}
</script>
2.通过调用createAPI
创建该组件的 API 。
import Vue from 'vue'
import Hello from './Hello.vue'
//如果装了'cube-ui'直接引入'cube-ui'就可以了
import CreateAPI from 'vue-create-api'
Vue.use(CreateAPI)
// 得到 this.$createHello API,它会添加到 Vue 原型上
Vue.createAPI(Hello, true)
3.在其他组件中调用this.$createHello
就完成了,hello组件就会被渲染在body上
methods: {
showHello() {
const instance = this.$createHello()
}
}
通过props传值
- Hello.vue 组件接收props
<template>
<div>
{{content}}
</div>
</template>
<script type="text/ecmascript-6">
export default {
name: 'hello',
props: {
content: {
type: String,
default: 'Hello'
}
}
}
</script>
- 调用
this.$createHello
时传入$props
methods: {
showHello() {
const instance = this.$createHello({
//1.8.0 版本后才能使用这种方式,普通的 js 文件中使用, $props 不具有响应式
$props:{content: "woshichuanrude"}
})
}
}
监听子组件事件
- Hello.vue 组件通过$emit传入事件名称来触发一个事件
<template>
<div @click="clickHandler">
{{content}}
</div>
</template>
<script type="text/ecmascript-6">
export default {
name: 'hello',
props: {
content: {
type: String,
default: 'Hello'
}
},
methods: {
clickHandler(e) {
this.$emit('click', e)
}
}
}
</script>
- 调用
this.$createHello
时通过$events监听事件
methods: {
showHello() {
const instance = this.$createHello({
//1.8.0 版本后才能使用这种方式,普通的 js 文件中使用, $props 不具有响应式
$props:{content: "woshichuanrude"},
$events: {
click() {
console.log('Hello component clicked.')
instance.remove() //删除组件
}
}
})
}
}
同理1.10.0 版本以后 config 中可以设置Vue 支持的所有的配置值,但是必须要加 $,例如:
this.$createHello({
$attrs: {
id: 'id'
},
$class: {
'my-class': true
}
})
插槽的使用
- Hello.vue 组件添加一个插槽
<template>
<div>
<slot name="other"></slot>
</div>
</template>
<script type="text/ecmascript-6">
export default {
name: 'hello',
props: {
content: {
type: String,
default: 'Hello'
}
}
}
</script>
- 调用
this.$createHello
中第二个参数传入renderFn函数
methods: {
showHello() {
const instance = this.$createHello(
{
//1.8.0 版本后才能使用这种方式,普通的 js 文件中使用, $props 不具有响应式
$props:{content: "woshichuanrude"}
},
createElement => {
return [
createElement(
"p",
{
slot: "other"
},
"other content"
)
];
})
}
}