# 定义新组件
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/07.%20%E5%BC%80%E5%8F%91%E6%8A%80%E5%B7%A7/04.%20%E5%AE%9A%E4%B9%89%E6%96%B0%E7%BB%84%E4%BB%B6


# 定义新组件

## 1.编写组件代码

> 例：封装一个可自定义前缀的输入框控件，组件

```js
<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 组件

```js
import JPrefixInput from './jeecg/components/JPrefixInput.vue';
 //...忽略
componentMap.set('JPrefixInput', JPrefixInput);
```

### 2.2 定义组件类型

> 在 `src/components/Form/src/types/index.ts` 中定义 JPrefixInput 组件类型，以便于在表单配置中设置

```js
export type ComponentType =
 // ...忽略
 | 'JPrefixInput'；
```

## 3.测试组件的使用

### 3.1 在表单中配置使用

```js
 //在表单中使用JPrefixInput组件
 {
    field: 'name',
    //2.2类型定义后，这里可以设置，不然会报错
    component: 'JPrefixInput',
    label: '前缀设置组件',
    componentProps: {
    //组件传参，设置前缀为 '姓名: '
      prefixStr: '姓名: ',
    },
    colProps: {
      span: 12,
    },
  },
  {
    field: 'name',
    component: 'JEllipsis',
    label: '输入值',
    colProps: { span: 12 },
  },
```

### 3.1 页面效果

![img](https://cdn.widiazine.com/obsidian/202408272319906.png)
