提交 | 用户 | 时间
|
820397
|
1 |
<script lang="tsx"> |
9259c2
|
2 |
import { computed, defineComponent, PropType } from 'vue' |
820397
|
3 |
import { isHexColor } from '@/utils/color' |
H |
4 |
import { ElTag } from 'element-plus' |
|
5 |
import { DictDataType, getDictOptions } from '@/utils/dict' |
9259c2
|
6 |
import { isArray, isBoolean, isNumber, isString } from '@/utils/is' |
820397
|
7 |
|
H |
8 |
export default defineComponent({ |
|
9 |
name: 'DictTag', |
|
10 |
props: { |
|
11 |
type: { |
|
12 |
type: String as PropType<string>, |
|
13 |
required: true |
|
14 |
}, |
|
15 |
value: { |
9259c2
|
16 |
type: [String, Number, Boolean, Array], |
820397
|
17 |
required: true |
9259c2
|
18 |
}, |
H |
19 |
// 字符串分隔符 只有当 props.value 传入值为字符串时有效 |
|
20 |
separator: { |
|
21 |
type: String as PropType<string>, |
|
22 |
default: ',' |
|
23 |
}, |
|
24 |
// 每个 tag 之间的间隔,默认为 5px,参考的 el-row 的 gutter |
|
25 |
gutter: { |
|
26 |
type: String as PropType<string>, |
|
27 |
default: '5px' |
820397
|
28 |
} |
H |
29 |
}, |
|
30 |
setup(props) { |
9259c2
|
31 |
const valueArr: any = computed(() => { |
H |
32 |
// 1. 是 Number 类型和 Boolean 类型的情况 |
|
33 |
if (isNumber(props.value) || isBoolean(props.value)) { |
|
34 |
return [String(props.value)] |
|
35 |
} |
|
36 |
// 2. 是字符串(进一步判断是否有包含分隔符号 -> props.sepSymbol ) |
|
37 |
else if (isString(props.value)) { |
|
38 |
return props.value.split(props.separator) |
|
39 |
} |
|
40 |
// 3. 数组 |
|
41 |
else if (isArray(props.value)) { |
|
42 |
return props.value.map(String) |
|
43 |
} |
|
44 |
return [] |
|
45 |
}) |
|
46 |
const renderDictTag = () => { |
820397
|
47 |
if (!props.type) { |
H |
48 |
return null |
|
49 |
} |
|
50 |
// 解决自定义字典标签值为零时标签不渲染的问题 |
9259c2
|
51 |
if (props.value === undefined || props.value === null || props.value === '') { |
820397
|
52 |
return null |
H |
53 |
} |
9259c2
|
54 |
const dictOptions = getDictOptions(props.type) |
H |
55 |
|
820397
|
56 |
return ( |
9259c2
|
57 |
<div |
H |
58 |
class="dict-tag" |
|
59 |
style={{ |
|
60 |
display: 'inline-flex', |
|
61 |
gap: props.gutter, |
|
62 |
justifyContent: 'center', |
|
63 |
alignItems: 'center' |
|
64 |
}} |
820397
|
65 |
> |
9259c2
|
66 |
{dictOptions.map((dict: DictDataType) => { |
H |
67 |
if (valueArr.value.includes(dict.value)) { |
|
68 |
if (dict.colorType + '' === 'primary' || dict.colorType + '' === 'default') { |
|
69 |
dict.colorType = '' |
|
70 |
} |
|
71 |
return ( |
|
72 |
// 添加标签的文字颜色为白色,解决自定义背景颜色时标签文字看不清的问题 |
|
73 |
<ElTag |
|
74 |
style={dict?.cssClass ? 'color: #fff' : ''} |
|
75 |
type={dict?.colorType || null} |
|
76 |
color={dict?.cssClass && isHexColor(dict?.cssClass) ? dict?.cssClass : ''} |
|
77 |
disableTransitions={true} |
|
78 |
> |
|
79 |
{dict?.label} |
|
80 |
</ElTag> |
|
81 |
) |
|
82 |
} |
|
83 |
})} |
|
84 |
</div> |
820397
|
85 |
) |
H |
86 |
} |
9259c2
|
87 |
return () => renderDictTag() |
820397
|
88 |
} |
H |
89 |
}) |
|
90 |
</script> |