定义新组件
1.编写组件代码
例:封装一个可自定义前缀的输入框控件,组件:JPrefixInput
<template>
<a-input v-bind="getBindValue" v-model:value="showText" @input="backValue" />
</template>
<script lang="ts">
import { defineComponent, ref, unref, watch, computed } from 'vue';
import { useAttrs } from '/@/hooks/core/useAttrs';
import { propTypes } from '/@/utils/propTypes';
import { omit } from 'lodash-es';
export default defineComponent({
name: 'JPrefixInput',
props: {
value: propTypes.string.def(''),
prefixStr: propTypes.string.def(''),
placeholder: propTypes.string.def(''),
},
emits: ['change', 'update:value'],
setup(props, { emit }) {
//属性
const attrs = useAttrs();
//表单显示文本值
const showText = ref('');
//组件绑定属性
const getBindValue = computed(() => {
return omit(Object.assign({}, unref(props), unref(attrs)), ['value']);
});
//监听value变化
watch(
() => props.value,
() => {
initVal();
},
{ immediate: true }
);
/**
* 初始化文本值
*/
function initVal() {
if (!props.value) {
showText.value = '';
} else {
let text = props.value;
showText.value = text ? text.replace(props.prefixStr, '') : text;
}
}
/**
* 返回文本值
*/
function backValue(e) {
let text = e?.target?.value ?? '';
if (props.prefixStr && text) {
text = props.prefixStr + text;
}
emit('change', text);
emit('update:value', text);
}
return { showText, attrs, getBindValue, backValue };
},
});
</script>
<style scoped></style>
2.定义类型和注册组件
2.1 注册组件
在
src/components/Form/src/componentMap.ts
中注册封装的JPrefixInput组件
import JPrefixInput from './jeecg/components/JPrefixInput.vue';
//...忽略
componentMap.set('JPrefixInput', JPrefixInput);
2.2 定义组件类型
在
src/components/Form/src/types/index.ts
中定义JPrefixInput组件类型,以便于在表单配置中设置
export type ComponentType =
// ...忽略
| 'JPrefixInput';
3.测试组件的使用
3.1 在表单中配置使用
//在表单中使用JPrefixInput组件
{
field: 'name',
//2.2类型定义后,这里可以设置,不然会报错
component: 'JPrefixInput',
label: '前缀设置组件',
componentProps: {
//组件传参,设置前缀为 '姓名: '
prefixStr: '姓名: ',
},
colProps: {
span: 12,
},
},
{
field: 'name',
component: 'JEllipsis',
label: '输入值',
colProps: { span: 12 },
},