基于Element UI库的Vue组件,实现了一个单选/多选框组合的效果,可以根据 type 属性的不同值来切换单选框(默认)和按钮式单选框/多选框。
创建组件index.vue (src/common-ui/radioGroup/index.vue)
<template>
<el-radio-group
v-model="hValue"
:size="size"
:disabled="disabled"
:text-color="textColor"
:fill="fill"
>
<template v-for="(item, index) in dataSource">
<el-radio-button
v-if="type === 'button'"
:key="index"
:label="item[hProps.value]"
:disabled="item[hProps.disabled]"
:name="item[hProps.name]"
>{{ item[hProps.label] }}</el-radio-button
>
<el-radio
v-else
:key="index+'else'"
:label="item[hProps.value]"
:disabled="item[hProps.disabled]"
:border="item[hProps.border] || border"
:size="item[hProps.size]"
:name="item[hProps.name]"
:class="{ vertical }"
>{{ item[hProps.label] }}</el-radio
>
</template>
</el-radio-group>
</template>
<script>
export default {
name: "HRadioGroup",
props: {
border: Boolean,
dataSource: {
type: Array,
label: [String, Number],
value: [String, Number, Boolean],
disabled: {
type: Boolean,
default: false
},
border: {
type: Boolean,
default: false
},
size: {
type: String,
validator(value) {
return ["medium", "small", "mini"].indexOf(value) !== -1;
}
},
name: String
},
disabled: {
type: Boolean,
default: false
},
fill: String,
size: {
type: String,
validator(value) {
return ["medium", "small", "mini"].indexOf(value) !== -1;
}
},
textColor: String,
type: {
type: String,
default: "normal",
validator(value) {
return ["normal", "button"].indexOf(value) !== -1;
}
},
value: {
type: [String, Number, Boolean]
},
vertical: Boolean,
props: {
type: Object,
default() {
return {};
}
}
},
computed: {
hValue: {
get() {
return this.value;
},
set(value) {
this.$emit("input", value);
this.$emit("change", value);
}
},
hProps() {
return {
label: "label",
value: "value",
disabled: "disabled",
border: "border",
size: "size",
name: "name",
...this.props
};
}
}
};
</script>
<style lang="scss" scoped>
.vertical {
display: block;
margin-left: 0 !important;
& + .vertical {
margin-top: 10px;
}
}
</style>
页面引入
- 在需要使用HRadioGroup组件的地方,通过import语句引入组件注册并使用
<template>
<div>
<h-radio-group
:value="selectedValue"
:data-source="dataSource"
@change="val => handleRadioGroupChange(val)"
>
</h-radio-group>
</div>
</template>
<script>
import HRadioGroup from '@/common-ui/radioGroup/index'
export default {
components: {
HRadioGroup
},
data() {
return {
filterVal: '',
dataSource: [],
selectedValue: ''
}
},
methods: {
handleRadioGroupChange(val, row) {
console.log(val,'选中的数据')
},
}
// ...
}
</script>
确保你已经安装了Vue.js和Element UI,并在项目中引入它们。