前言
数据字典 作为前端与后台开发的命名约定,在日常开发中很多地方都会使用到,如 性别、种类等。接口请求以id传输,反馈到页面上显示对应的name。这种可以统一封装成一个接口作为 数据字典 进行交互。
实现
在 data
下定义数组 dicData
作为存储当前页需要的数据字典。
注:如果有子组件,建议在父组件中把所需数据字典统一请求到,并当成参数传递给子组件直接使用,避免重复请求多次数据字典的接口。
vue项目中可在 created
生命周期中直接调用接口获取需要的数据字典。
created(){
this.getDic();
},
methods:{
getDic(){
airPost('', this.$dicUrl, {
typeIds: ['12345', '67890']
}).then(res => {
let {content, message, code} = res.data;
if (code === '0000') {
this.dicData = content.list;
} else {
this.$message({message: message, type:'error'});
}
})
},
getDicById(id, typeId){
return getDicById(id,typeId,this.dicData);
}
}
引入数据字典的方法
import { getDicById } from '@/utils/common.js';
页面中需要双向绑定显示的地方
{{ getDicById(source, 12345).label }}
在 common.js
中封装的函数
/*
* @param id {String} 数据字典key
* @param typeId {String} 数据字典typeId
* @param dicArr {Array} 多个数据字典的集合
* @param name {String} 数据字典val
*/
export function getDicById (id='', typeId, dicArr=[], name='') {
let currentDicArr = dicArr,
typeArray = currentDicArr.find(item => item.typeid === typeId),
array = typeArray && typeArray.itemsList ? typeArray.itemsList : [],
label = '',
key = ''
if (id !== '') {
let item = array.find(item => item.dicKey === id)
if (item) {
label = item.dicVal
} else {
label = '-'
}
}
if (name != '') {
let item = array.find(item => item.dicVal === name)
if (item) {
key = item.dicKey
}
}
return {
label,
array,
key
}
}
PS:写作不易,如要转裁,请标明转载出处。