preface

As the naming convention of front-end and back-end development, data dictionary is used in many places in daily development, such as gender and category. The interface request is transmitted by ID, and the corresponding name is displayed on the page. This can be encapsulated as a unified interface to interact as a data dictionary.

implementation

Define the array dicData under DATA as the data dictionary needed to store the current page. Note: If there is a child component, it is recommended to request the required data dictionary in the parent component and pass it as a parameter to the child component for direct use, avoiding the interface that repeatedly requests the data dictionary. A VUE project can call the interface directly during the Created life cycle to get the required data dictionary.

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); }}Copy the code

The introduction of data dictionary methods

import { getDicById } from '@/utils/common.js';
Copy the code

The part of the page where the bidirectional binding display is required

{{ getDicById(source, 12345).label }}
Copy the code

Functions encapsulated in common.js

/* * @param id {String} data dictionary key * @param typeId {String} data dictionary typeId * @param dicArr {Array} multiple data dictionary set * @param name Var */ 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 } }Copy the code

PS: Writing is not easy, if you want to cut, please indicate the source of reprint.