> 文章列表 > Vue项目中查字典匹配值

Vue项目中查字典匹配值

Vue项目中查字典匹配值

一、业务场景:
列表中状态较多,为了避免写许多switch或if判断,后台给了个字典

二、实现思路
1.封装一个获取字典类型列表的方法(调接口)
2.封装一个匹配状态的方法(根据状态显示想要的文字)

三、具体实现步骤:

先拿到字典类型的表(数组)

/* 根据类型获取字典内容 返回数组* @param {String} dictType 字典类型*/
export function getDictArray(dictType) {return new Promise((resolve, reject) => {const dict = store.getters.getDict(dictType)if (dict) {resolve(dict)return}// 获取字典类型表axios({url: api.dictData + '/type',method: 'get',params: { dictType: dictType }}).then((response) => {store.commit(SET_DICT, {type: dictType,data: response})resolve(response)}).catch((error) => {reject(error)})})
}

字典匹配的方法

export function covertDictForList(list, value, attrVal = 'dictValue', attrName = 'dictLabel') {const data = list.filter((obj) => {return obj[attrVal] === value || obj[attrVal] + '' === value + ''})if (data.length !== 0) {return data[0][attrName]}return ''
}

在要使用的界面引入

import { getDictArray } from '@/utils/dict'

进入页面加载一下

  async mounted() {this.personLvList = await getDictArray('ryxx_person_lv')},

在需要匹配的表格里直接调用查询方法

      <span slot="ryRyxx.level" slot-scope="text"><span :class="[level(text)]"> {{ text !== null ? covertDictForList(personLvList, text) : '无' }}</span></span>

四、效果展示:
Vue项目中查字典匹配值

你已经成功了,撒花。
今天的分享到此结束,欢迎小伙伴们一起交流