/* * @Author: yourcandy * @Date: 2021-07-14 23:34:34 * @LastEditTime: 2021-07-14 23:34:34 * @LastEditors: wpf * @Description:局部混入 字典公共请求封装 (主要针对后端只支持传入单个字典的封装) * @FilePath: \ztocwst-capacitycenter-webc:\Users\Admin\Desktop\initDict.js */import { getDictRequest } from '@/api/dict'export default { data() { return { dicts: [], dictMap: {}, } }, methods: { /** * 请求单个字典 * @description : * @param {String} name 要请求的字典名 * @return {Array} */ async getDict(name) { return new Promise((resolve, reject) => { getDictRequest(name) .then((res) => { this.dicts = res resolve(res) }) .catch((err) => { reject(err) }) }) }, /** * 请求多个字典 * @description: 多个字典查询时使用逗号拼接, 如: this.getDictMap('user_status,job_status') 使用加载出来的字典:dictMap.[字典名称] 如:dictMap.user_status * @param {*} names * @return {*} */ async getDictMap(names) { // 优先放入到dictMap中,避免页面加载时 undefined const arr = names.split(',') let getDictArray = [] for (let i = 0; i < arr.length; i++) { this.dictMap[arr[i]] = [] getDictArray.push(this.getDict(arr[i])) } return new Promise((resolve, reject) => { Promise.all(getDictArray) .then((result) => { for (let i = 0; i < arr.length; i++) { this.dictMap[arr[i]] = result[i] let obj = {} for (let item of result[i]) { obj[item.dictType] = item.dictName } } resolve(this.dictMap) }) .catch((err) => { reject(err) }) }) }, },}
/* * @Author: yourcandy * @Date: 2021-07-14 23:34:34 * @LastEditTime: 2021-07-14 23:34:34 * @LastEditors: wpf * @Description:局部混入 字典公共请求封装 (主要针对后端支持传入数组的多个字典的封装) * @FilePath: \ztocwst-capacitycenter-webc:\Users\Admin\Desktop\initDict.js */export default { data() { return { dictMap: {} }; }, methods: { // 初始化字典 intiDict(dicType) { return new Promise((resolve, reject) => { this.Http('xxxxxxxxxxurl', { ignoreRepeat: true, dicType }).then((res) => { this.dictMap = this.groupBy(res, v => v.dicType); resolve(res); }); }); }, // 字典分组 groupBy(array, f) { let obj = {}; array.forEach((v) => { let key = f(v); if (obj.hasOwnProperty(key)) { obj[key].push(v); } else { obj[key] = [v]; } }); return obj; } }};
/* * @Author: yourcandy * @Date: 2021-07-14 23:34:34 * @LastEditTime: 2021-07-14 23:34:34 * @LastEditors: wpf * @Description:局部混入 字典公共请求封装 (主要针对后端支持传入数组的多个字典的封装) * @FilePath: \ztocwst-capacitycenter-webc:\Users\Admin\Desktop\initDict.js */export default { data() { return { dicData: {} }; }, methods: { /** * 查询字典 * @param {Array} dicTypes */ getDict(dicTypes) { // 先赋值默认值 this.dicData = dicTypes.reduce((total, item) => { total[item] = []; return total; }, {}); this.Http('xxxxurl', { ignoreRepeat: true, dicTypes }).then(res => { this.dicData = res.result.reduce((total, item) => { if (total[item.dicType]) { total[item.dicType].push(item); } else { total[item.dicType] = [item]; } return total; }, {}); console.log(this.dicData); }); } }};