code-list.tsx 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
import { ref, watch, defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import { isNil } from 'ramda';
import './code-list.scss';

export const CodeList = defineComponent({
  props: {
    codeListItems: {
      type: Array<IData>,
    },
    codeList: {
      type: Object,
      required: true,
    },
    value: {
      type: [String, Number],
    },
  },
  setup(props) {
    const ns = useNamespace('code-list');
    const items = ref<IData[]>([]);

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (isNil(newVal) || newVal === '') {
            // 空值置空
            items.value = [];
          } else {
            // 非空值解析代码表
            let values: string[] | number[];
            if (typeof newVal === 'string') {
              values = newVal.split(',');
            } else {
              values = [newVal];
            }
            items.value = values.map(val => {
              const findItem = props.codeListItems?.find(
                item => item.value === val,
              );
              return {
                text: findItem?.text || val,
                color: findItem?.color,
              };
            });
          }
        }
      },
      { immediate: true },
    );

    return { items, ns };
  },
  render() {
    if (this.items.length === 0) {
      return this.codeList.emptyText;
    }
    return (
      <span class={this.ns.b()}>
        {this.items.map((item, index) => {
          return [
            index !== 0 ? this.codeList?.textSeparator : null,
            <span
              class={this.ns.e('item')}
              style={this.ns.cssVarBlock({
                'item-color': `${item.color}`,
              })}
            >
              {item.text}
            </span>,
          ];
        })}
      </span>
    );
  },
});