封装utils/dict.js
javascript
// 这部分代码是模拟查询后端接口---开始
const dictionaries = {
STATUS: [
{ name: '启用', key: '0' },
{ name: '禁用', key: '1' }
],
TYPE: [
{ name: '类型A', key: '00' },
{ name: '类型B', key: '01' },
{ name: '类型C', key: '02' }
]
}
export function queryDictList(dictType) {
const options = dictionaries[dictType] || []
return Promise.resolve({
data: options,
code: 200,
message: '查询成功'
})
}
// 这部分代码是模拟查询后端接口---结束
// ============正式的utils/dict.js代码从这里开始
const LabelKey = 'name';
const ValueKey = 'key';
const cache = {};
const pending = {};
/**
* 查询字典数据
*/
function loadRaw(dictType) {
if (cache[dictType]) {
return Promise.resolve(cache[dictType]);
}
if (pending[dictType]) {
return pending[dictType];
}
pending[dictType] = queryDictList(dictType)
.then(res => {
cache[dictType] = res.data;
return cache[dictType];
}).catch().finally(() => {
delete pending[dictType];
});
return pending[dictType];
}
/**
* 读取单个字典
*/
export async function getDict(dictType) {
const raw = await loadRaw(dictType);
return raw.map(i => {
return {
label: i[LabelKey],
value: i[ValueKey]
};
})
}
/**
* 批量读取多个字典
*/
export function preloadDicts(...types) {
return Promise.all(types.map(getDict));
}
/**
* 根据值获取字典标签
*/
export function getDictLabel(dictType, value) {
const raw = cache[dictType];
if (!raw) {
return value;
}
const item = raw?.find(i => i[ValueKey] === value);
return item ? item[LabelKey] : value;
}
/**
* 清空字典数据
*/
export function clearDictCache(dictType) {
if (dictType) {
delete cache[dictType];
} else {
Object.keys(cache).forEach(key => delete cache[key]);
}
}
使用场景
列表中渲染字典label
在main.js中注册成全局方法
javascript
import { getDictLabel } from './utils/dict'
Vue.prototype.$dictLabel = getDictLabel
页面初始化时查询字典数据
javascript
import { preloadDicts } from '../utils/dict';
async created() {
// 加载字典数据
await preloadDicts('STATUS', 'TYPE');
},
页面模板中使用
html
<el-table :data="tableData" border>
<el-table-column prop="type" label="类型" min-width="180">
<template slot-scope="scope">
{{ $dictLabel('TYPE', scope.row.type) }}
</template>
</el-table-column>
<el-table-column prop="status" label="状态" min-width="180">
<template slot-scope="scope">
{{ $dictLabel('STATUS', scope.row.status) }}
</template>
</el-table-column>
</el-table>
表单中字典下拉框数据绑定
封装components/DictSelect.vue组件
html
<template>
<el-select
v-bind="$attrs"
:value="value"
:loading="loading"
style="width: 100%"
@input="$emit('input', $event)"
@change="$emit('change', $event)"
>
<el-option
v-for="option in optionList"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</template>
<script>
import { getDict } from '../utils/dict'
export default {
name: 'DictSelect',
props: {
dictType: {
type: String,
required: true
},
value: {
type: [String, Number],
default: undefined
},
},
data() {
return {
optionList: [],
loading: false,
requestId: 0
}
},
watch: {
dictType: {
immediate: true,
handler(dictType) {
this.loadOptions(dictType)
}
}
},
methods: {
async loadOptions(dictType) {
const requestId = ++this.requestId
this.optionList = []
if (!dictType) {
this.loading = false
return
}
this.loading = true
try {
const options = await getDict(dictType)
if (requestId === this.requestId) {
this.optionList = options
}
} catch (error) {
if (requestId === this.requestId) {
this.optionList = []
this.$emit('load-error', error)
}
} finally {
if (requestId === this.requestId) {
this.loading = false
}
}
}
}
}
</script>
页面中注册组件
javascript
import DictSelect from '../components/DictSelect.vue'
export default {
name: 'DictDemo',
components: {
DictSelect
},
};
页面模板中使用
html
<el-form ref="entryForm" :model="form" :rules="rules" label-position="top">
<el-form-item label="类型" prop="type">
<DictSelect v-model="form.type" dictType="TYPE" clearable size="small" />
</el-form-item>
<el-form-item label="状态" prop="status">
<DictSelect v-model="form.status" dictType="STATUS" clearable size="small"/>
</el-form-item>
</el-form>