vben
2020-12-25 4ff1c408dc1acfc49e0adc61dc2e539c0c198158
提交 | 用户 | age
4ff1c4 1 <!--
V 2  * @Description:It is troublesome to implement radio button group in the form. So it is extracted independently as a separate component
3 -->
4
1d4561 5 <template>
4ff1c4 6   <RadioGroup v-bind="attrs" v-model:value="state" button-style="solid">
1d4561 7     <template v-for="item in getOptions" :key="`${item.value}`">
V 8       <RadioButton :value="item.value"> {{ item.label }} </RadioButton>
9     </template>
10   </RadioGroup>
11 </template>
12 <script lang="ts">
4ff1c4 13   import { defineComponent, PropType, computed } from 'vue';
1d4561 14   import { Radio } from 'ant-design-vue';
V 15   import { isString } from '/@/utils/is';
4ff1c4 16   import { useRuleFormItem } from '/@/hooks/component/useFormItem';
V 17   import { useAttrs } from '/@/hooks/core/useAttrs';
1d4561 18   type OptionsItem = { label: string; value: string; disabled?: boolean };
V 19   type RadioItem = string | OptionsItem;
4ff1c4 20
1d4561 21   export default defineComponent({
V 22     name: 'RadioButtonGroup',
23     components: {
24       RadioGroup: Radio.Group,
25       RadioButton: Radio.Button,
26     },
27     props: {
28       value: {
29         type: String as PropType<string>,
30       },
31       options: {
32         type: Array as PropType<RadioItem[]>,
33         default: () => [],
34       },
35     },
4ff1c4 36     setup(props) {
V 37       const attrs = useAttrs();
38       // Embedded in the form, just use the hook binding to perform form verification
39       const [state] = useRuleFormItem(props);
40       // Processing options value
1d4561 41       const getOptions = computed((): OptionsItem[] => {
V 42         const { options } = props;
4ff1c4 43         if (!options || options?.length === 0) return [];
V 44
1d4561 45         const isStringArr = options.some((item) => isString(item));
V 46         if (!isStringArr) return options as OptionsItem[];
4ff1c4 47
1d4561 48         return options.map((item) => ({ label: item, value: item })) as OptionsItem[];
V 49       });
50
4ff1c4 51       return { state, getOptions, attrs };
1d4561 52     },
V 53   });
54 </script>