为什么写这个?
想找到以下几个问题的解决方案:
- 封装JSON表单组件(完全通过JSON完成表单初始化),在表单组件内部怎么使用父组件中局部注册的组件
- 封装JSON表格组件(完全通过JSON完成表格初始化),自定义单元格内容怎么实现
实现示例
实现方式:通过JSX以及render/h渲染函数来
示例
<!-- Demo.vue -->
<script lang="tsx" setup>
import { ref } from 'vue'
import TableCell from 'components/TableCell'
import MyTag from './MyTag.vue'
const myName = ref<string>('小三子')
function onChangeMyName() {
myName.value = '大三子' + new Date().toString()
}
function customRender(tmpName: string) {
return <div>不错:{tmpName}</div>
}
</script>
<template>
<hr />
<button @click="onChangeMyName">按钮</button>
<hr />
<TableCell :my-name="myName"></TableCell>
<hr />
<TableCell :my-name="myName" :custom-render="customRender"></TableCell>
<hr />
<TableCell :my-name="myName" :custom-tag="MyTag"></TableCell>
<hr />
</template>
// TableCell.tsx
import { defineComponent, h } from 'vue'
export default defineComponent({
name: 'TableCell',
props: {
myName: {
type: String,
required: false,
},
customRender: {
type: Function,
required: false,
},
customTag: {
type: Object,
required: false,
},
},
render(context: any) {
console.log('context', context)
if (context.customRender) {
return context.customRender(context.myName)
} else if (context.customTag) {
return h(context.customTag, { myName: context.myName })
} else {
return h('div', '你好' + context.myName)
}
},
})
<!--
MyTag.vue
-->
<script lang="ts" setup>
defineProps<{
myName?: string
}>()
function onClick() {
console.log('点击事件也是有效的')
}
</script>
<template>
<div>
<strong>我的标签</strong>
<h3>{{ myName }}</h3>
<el-button @click="onClick">Element Plus 按钮</el-button>
</div>
</template>
<style lang="scss" scoped></style>
效果