| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- <template>
- <view class="dict-tag" :class="tagClass">{{ label }}</view>
- </template>
- <script setup>
- import { computed, getCurrentInstance, onMounted } from 'vue'
- import { useDict } from '@/utils/composables/useDict'
- const props = defineProps({
- // 字典类型
- dictType: {
- type: String,
- required: true
- },
- // 字典值
- value: {
- type: [String, Number],
- required: true
- },
- // 是否带颜色样式
- colored: {
- type: Boolean,
- default: true
- }
- })
- // 获取当前组件实例,用于访问父组件
- const instance = getCurrentInstance()
- // 初始化字典功能,但不自动加载
- const { dictData, loadDict, getDictLabel, getDictClass } = useDict([], { autoLoad: false })
- // 查找已加载指定字典类型的父组件
- const findParentWithDict = (dictType) => {
- let parent = instance.parent
- while (parent) {
- // 检查父组件是否有 dictData 并且包含指定类型的字典
- if (parent.ctx && parent.ctx.dictData && parent.ctx.dictData[dictType]) {
- console.log(`[DictTag] Found parent with dictionary ${dictType} already loaded`)
- return parent.ctx
- }
- parent = parent.parent
- }
- console.log(`[DictTag] No parent found with dictionary ${dictType}, loading it independently`)
- return null
- }
- // 计算属性:字典标签
- const label = computed(() => {
- return getDictLabel(props.dictType, props.value, '')
- })
- // 计算属性:标签样式类
- const tagClass = computed(() => {
- if (!props.colored) return ''
- const className = getDictClass(props.dictType, props.value, '')
- return className ? `tag-${className}` : ''
- })
- // 组件挂载时加载字典
- onMounted(() => {
- // 检查父组件是否已加载此字典
- const parentWithDict = findParentWithDict(props.dictType)
-
- if (parentWithDict) {
- // 父组件已加载此字典,使用父组件的字典数据
- if (parentWithDict.dictData && parentWithDict.dictData[props.dictType]) {
- dictData[props.dictType] = parentWithDict.dictData[props.dictType]
- }
- } else {
- // 父组件未加载此字典,自己加载
- loadDict([props.dictType])
- }
- })
- </script>
- <style scoped>
- .dict-tag {
- display: inline-block;
- padding: 0 10rpx;
- height: 40rpx;
- line-height: 40rpx;
- font-size: 26rpx;
- color: #666;
- border-radius: 20rpx;
- text-align: center;
- white-space: nowrap;
- }
- .tag-primary {
- color: #fff;
- background-color: #409EFF;
- }
- .tag-success {
- color: #fff;
- background-color: #67C23A;
- }
- .tag-info {
- color: #fff;
- background-color: #909399;
- }
- .tag-warning {
- color: #fff;
- background-color: #E6A23C;
- }
- .tag-danger {
- color: #fff;
- background-color: #F56C6C;
- }
- .tag-secondary {
- color: #fff;
- background-color: #8A69F9;
- }
- .tag-default {
- color: #333;
- background-color: #E9E9E9;
- }
- </style>
|