You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.5 KiB

<template>
<el-form-item :class="[{'column':column},'form-item']" :label="label" :prop="prop" :rules="rules" :required="required">
<el-radio-group v-model="selectedValue" v-bind="$attrs" @change="handleChange">
<el-radio
v-for="option in processedOptions"
:key="getValue(option)"
:label="getValue(option)"
:disabled="option.disabled"
>
{{ getLabel(option) }}
</el-radio>
</el-radio-group>
</el-form-item>
</template>
<script>
export default {
name: 'MyRadioGroup',
props: {
// 是否是纵向排列
column:{
type:String,
default:''
},
required:{
type:Boolean,
default:false
},
// 选项列表,格式为 [{ label: '显示文本', value: '值', disabled: false }]
options: {
type: Array,
required: true,
},
// 当前选中的值,使用 v-model 绑定
value: {
type: [String, Number, Boolean],
default: '',
},
// 表单项的 label
label: {
type: String,
default: '',
},
// 表单项的 prop(用于表单校验)
prop: {
type: String,
default: '',
},
// 校验规则
rules: {
type: Array,
default: () => [],
},
labelKey: {
type: String,
default: 'label'
},
// 自定义value的字段名
valueKey: {
type: String,
default: 'value'
},
// 格式化label的函数
formatter: {
type: Function,
default: null
}
},
computed: {
processedOptions() {
return this.options.map(option => {
if (this.formatter) {
return {
...option,
formattedLabel: this.formatter(option)
}
}
return option
})
}
},
data() {
return {
selectedValue: this.value, // 内部维护的选中值
};
},
watch: {
// 监听外部传入的 value 变化,更新内部 selectedValue
value(newVal) {
this.selectedValue = newVal;
},
},
methods: {
// 选中值变化时触发
handleChange(value) {
this.$emit('input', value); // 更新 v-model
this.$emit('change', value); // 触发 change 事件
},
getLabel(option) {
if (this.formatter) return option.formattedLabel || this.formatter(option)
return option[this.labelKey]
},
getValue(option) {
return option[this.valueKey]
},
},
};
</script>
<style scoped>
/* 自定义样式 */
.el-radio-group {
margin: 10px 0;
}
</style>