一、前端可以很多字段后台传过来的为字典id,前端需要展示id对应名称
1.全部转换格式,适合全局使用(暂时在小程序上使用)
//调取接口获得数据 dataList: function() { resume.dataList().then(res => { //下面为主要方法 var dict={} var trade = {} Object.keys(res.data).map(key => { dict[key]= res.data[key].map(i => { trade[i.id]=i.dictValue }); wx.setStorageSync('dictType', trade) getApp().globalData.dictType = trade }); }) .catch(res => {}) }, data: { COMPANY_LOGIN_TYPE: [ 0: {defId: 23, deleteFlag: 0, description: "企业账号类型", dictValue: "主账号", editable: 0, id: 113, seqIndex: 0} 1: {defId: 23, deleteFlag: 0, description: "企业账号类型", dictValue: "次账号", editable: 0, id: 114, seqIndex: 0} ], COMPANY_TYPE: [ 0: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "外资", editable: 0, id: 23, seqIndex: 0} 1: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "合资", editable: 0, id: 24, seqIndex: 1} 2: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "国企", editable: 0, id: 25, seqIndex: 2} 3: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "民营公司", editable: 0, id: 26, seqIndex: 3} 4: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "上市公司", editable: 0, id: 27, seqIndex: 4} 5: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "创业公司", editable: 0, id: 28, seqIndex: 5} 6: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "政府机关", editable: 0, id: 29, seqIndex: 6} 7: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "事业单位", editable: 0, id: 30, seqIndex: 7} 8: {defId: 5, deleteFlag: 0, description: "企业类型", dictValue: "非营利机构", editable: 0, id: 31, seqIndex: 8} ] }将字典表转换为对象格式,id为键,值为名称
取值是这样
<view class="basic-essential-text">{{dictType[educationalId]}} </view> <!-- //[]里面填写字典表id的值 //js里面在onLoad里面拿到这个对象 // this.setData({ // dictType:app.globalData.dictType }); -->2.封装一个方法,小程序上不像前端主流框架那样可以实现双向绑定,也不能在HTML中直接写js(适用vue和react),小程序的方法也可适用大部分js根据id查名称需求。(主要就是重新遍历一遍字典表,转换成自己好取值的方法)
import { GET } from "@/base/request"; //这步是调取接口获得数据//vue,react的方法,包括一些UI框架封装的发法都不一样,只是获取数据,数据结构同上表 const getAllDict = async function() { const res = await GET("/dict/data/list"); if (res.code === "ACK") { //这里主要方法,将字段表遍历一遍id和名称做成一个对象 Object.keys(res.data).map(key => { dict[key] = res.data[key].map(i => { return { label: i.dictValue, value: i.dictId }; }); }); // } }; // 匹配名字 const dictName = function(id, name) { if (dict[name]) { const res = dict[name].filter(i => i.value === id); if (res.length > 0) { return res[0].label; } return "-"; } else { return "-"; } }; export { dictName, dict, getAllDict }; import { dictName } from "../../base/dict.js"; //在methods里面加入dictName//此处用vue的方法 methods: { dictName }, //标签里面写方法就能找到id对应的名称 <p>{{dictName(data.userInfo.type ,'USER_TYPE')}}</p>3.单个id匹配名称(以上两个方法适合做全局,大量id匹配Value)
//此为小程序方法,vue和react方法雷同,react中state 和data就基本相同 //拿到要查找的id let educational = this.data.educational; //this.data.columns为数组,就从这个数组中找id对应的值,find方法 //找到id和数组中id相等 var obj = this.data.columns.find(function (obj) { return obj.dictId === educational; }); //返回完拿obj.value就为id对应的名称