Vue实现数据字典
Vue 数据字典的实现方法
数据字典在项目中常用于存储固定选项(如状态、类型等),Vue 中可通过以下方式实现:
全局注册字典数据
在 main.js 或单独模块中定义全局字典:
// 字典定义
const dicts = {
status: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 }
],
gender: [
{ label: '男', value: 'male' },
{ label: '女', value: 'female' }
]
}
// 挂载到Vue原型
Vue.prototype.$dicts = dicts
组件内使用方式:
this.$dicts.status // 获取状态字典
使用 Vuex 管理字典
适用于需要动态更新字典的场景:
// store/modules/dict.js
export default {
state: {
dictData: {}
},
mutations: {
SET_DICT(state, { key, data }) {
state.dictData[key] = data
}
},
actions: {
async fetchDict({ commit }, key) {
const res = await api.getDict(key)
commit('SET_DICT', { key, data: res.data })
}
}
}
组件调用示例:
this.$store.dispatch('fetchDict', 'status')
封装字典组件
创建可复用的字典组件:
<template>
<select v-model="selected">
<option
v-for="item in dictData"
:key="item.value"
:value="item.value"
>
{{ item.label }}
</option>
</select>
</template>
<script>
export default {
props: ['dictKey'],
computed: {
dictData() {
return this.$dicts[this.dictKey] || []
}
}
}
</script>
动态加载字典
配合 API 实现按需加载:
export default {
data() {
return {
statusOptions: []
}
},
created() {
this.loadDict('status')
},
methods: {
async loadDict(key) {
const res = await axios.get(`/api/dict/${key}`)
this[`${key}Options`] = res.data
}
}
}
类型安全实现(TypeScript)
使用 TS 增强类型检查:
interface DictItem {
label: string
value: string | number
}
type DictKey = 'status' | 'gender'
const dicts: Record<DictKey, DictItem[]> = {
status: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 }
]
}
// 组件中使用
@Component
export default class extends Vue {
get statusOptions(): DictItem[] {
return this.$dicts.status
}
}
最佳实践建议
- 对于静态字典,推荐使用全局注册方式减少重复代码
- 动态字典建议通过 Vuex 管理状态,保持数据一致性
- 大型项目可将字典分类为多个模块(如
userDict、orderDict) - 考虑添加字典缓存机制,避免重复请求
以上方案可根据项目复杂度组合使用,小型项目使用全局注册即可满足需求,中大型项目建议结合 Vuex 和组件封装。







