Vue2项目中数据字典的使用封装

封装utils/dict.js

javascript 复制代码
// 这部分代码是模拟查询后端接口---开始
const dictionaries = {
  STATUS: [
    { name: '启用', key: '0' },
    { name: '禁用', key: '1' }
  ],
  TYPE: [
    { name: '类型A', key: '00' },
    { name: '类型B', key: '01' },
    { name: '类型C', key: '02' }
  ]
}

export function queryDictList(dictType) {
  const options = dictionaries[dictType] || []
  return Promise.resolve({
    data: options,
    code: 200,
    message: '查询成功'
  })
}
// 这部分代码是模拟查询后端接口---结束

// ============正式的utils/dict.js代码从这里开始
const LabelKey = 'name';
const ValueKey = 'key';
const cache = {};
const pending = {};

/**
 * 查询字典数据
 */
function loadRaw(dictType) {
  if (cache[dictType]) {
    return Promise.resolve(cache[dictType]);
  }
  if (pending[dictType]) {
    return pending[dictType];
  }
  pending[dictType] = queryDictList(dictType)
    .then(res => {
      cache[dictType] = res.data;
      return cache[dictType];
    }).catch().finally(() => {
      delete pending[dictType];
    });
    return pending[dictType];
}

/**
 * 读取单个字典
 */
export async function getDict(dictType) {
  const raw = await loadRaw(dictType);
  return raw.map(i => {
    return {
      label: i[LabelKey],
      value: i[ValueKey]
    };
  })
}

/**
 * 批量读取多个字典
 */
export function preloadDicts(...types) {
  return Promise.all(types.map(getDict));
}

/**
 * 根据值获取字典标签
 */
export function getDictLabel(dictType, value) {
  const raw = cache[dictType];
  if (!raw) {
    return value;
  }
  const item = raw?.find(i => i[ValueKey] === value);
  return item ? item[LabelKey] : value;
}

/**
 * 清空字典数据
 */
export function clearDictCache(dictType) {
  if (dictType) {
    delete cache[dictType];
  } else {
    Object.keys(cache).forEach(key => delete cache[key]);
  }
}

使用场景

列表中渲染字典label

在main.js中注册成全局方法

javascript 复制代码
import { getDictLabel } from './utils/dict'

Vue.prototype.$dictLabel = getDictLabel

页面初始化时查询字典数据

javascript 复制代码
import { preloadDicts } from '../utils/dict';
 
 async created() {
    // 加载字典数据
    await preloadDicts('STATUS', 'TYPE');
  },

页面模板中使用

html 复制代码
<el-table :data="tableData" border>
 <el-table-column prop="type" label="类型" min-width="180">
   <template slot-scope="scope">
	 {{ $dictLabel('TYPE', scope.row.type) }}
   </template>
 </el-table-column>

 <el-table-column prop="status" label="状态" min-width="180">
	<template slot-scope="scope">
	 {{ $dictLabel('STATUS', scope.row.status) }}
	</template>
 </el-table-column>
</el-table>

表单中字典下拉框数据绑定

封装components/DictSelect.vue组件

html 复制代码
<template>
  <el-select
    v-bind="$attrs"
    :value="value"
    :loading="loading"
    style="width: 100%"
    @input="$emit('input', $event)"
    @change="$emit('change', $event)"
  >
    <el-option
      v-for="option in optionList"
      :key="option.value"
      :label="option.label"
      :value="option.value"
    />
  </el-select>
</template>

<script>
import { getDict } from '../utils/dict'

export default {
  name: 'DictSelect',
  props: {
    dictType: {
      type: String,
      required: true
    },
    value: {
      type: [String, Number],
      default: undefined
    },
  },
  data() {
    return {
      optionList: [],
      loading: false,
      requestId: 0
    }
  },
  watch: {
    dictType: {
      immediate: true,
      handler(dictType) {
        this.loadOptions(dictType)
      }
    }
  },
  methods: {
    async loadOptions(dictType) {
      const requestId = ++this.requestId
      this.optionList = []

      if (!dictType) {
        this.loading = false
        return
      }

      this.loading = true
      try {
        const options = await getDict(dictType)
        if (requestId === this.requestId) {
          this.optionList = options
        }
      } catch (error) {
        if (requestId === this.requestId) {
          this.optionList = []
          this.$emit('load-error', error)
        }
      } finally {
        if (requestId === this.requestId) {
          this.loading = false
        }
      }
    }
  }
}
</script>

页面中注册组件

javascript 复制代码
import DictSelect from '../components/DictSelect.vue'

export default {
	name: 'DictDemo',
	components: {
      DictSelect
	},
};

页面模板中使用

html 复制代码
<el-form ref="entryForm" :model="form" :rules="rules" label-position="top">
	<el-form-item label="类型" prop="type">
         <DictSelect v-model="form.type" dictType="TYPE" clearable size="small" />
	</el-form-item>

	<el-form-item label="状态" prop="status">
         <DictSelect v-model="form.status" dictType="STATUS" clearable size="small"/>
	</el-form-item>
</el-form>
相关推荐
map_vis_3d43 分钟前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
kyriewen1 小时前
我把 7 个 UI 库的下拉框用键盘敲了一遍,3 家出了岔子
前端·javascript·程序员
陈随易1 小时前
MoonBit 2026 深圳线下交流分享
前端·后端·程序员
玖米GEO运营王总监1 小时前
抖音和视频号算法区别:玖米快跑的双端分发信号与内容适配对比
java·前端·人工智能
鼓掌MVP1 小时前
华为云码道实战:用 CodeArts Agent + 智能化搜索工具 API 调用自主开发「非遗文旅宣传卡生成器」
前端·人工智能·ai·html·ai编程·ai智能体·ai自动化
不要试图纠正别人2 小时前
1055 个文件,共享 0 字节:pnpm 硬链接的静默降级
前端·node.js
tryCbest2 小时前
Vue系列——第 24 篇:VueUse——组合式工具集的百宝箱
前端·vue.js
GuWenyue2 小时前
setInterval 里的 state 永远是 0?我把 React 闭包陷阱的 5 个反例全写了一遍
前端·react.js
Xeni2 小时前
从「会写」到「真懂」:SSE 流式输出的 20 行代码与 7 个坑
前端