原理:全局使用Vue的混入(mixin),来实现页面创建时进行请求后端字典列表,然后在页面通过该列表进行翻译字典。
1. 创建 Dict 类
首先创建一个 dict 文件夹,再在这个文件夹下创建 Dict.js,如下
import Vue from 'vue'
import request from '@/utils/request';
export default class Dict {
constructor() {
this.type = {}
}
async init(options) {
// options 是页面定义的 dicts 列表,表明要请求哪些类型的字典
for (let type of options) {
// 使用 Vue.set 方法来初始化指定类型列表,否则页面将获取不到
Vue.set(this.type, option, [])
// 这里是请求后端的字典接口
const res = await request({
url: `localhost:8080/getDictList?type=${type}`,
method: 'get'
});
const data = res.data;
// 将请求后的字典添加到指定 type 列表
this.type[type].splice(0, Number.MAX_SAFE_INTEGER, ...data);
}
}
}
2. 创建全局混入
创建 dictMixin.js 文件,如下
import Dict from "./Dict";
export default function (Vue, options) {
Vue.mixin({
data() {
// 如果页面没有设置 dicts 属性,则不创建 dict 属性
if (this.$options === undefined || this.$options.dicts === undefined || this.$options.dicts === null) {
return {}
}
const dict = new Dict();
return {
dict
}
},
methods: {
// 翻译字典(根据字典列表和字典值,获取指定字典描述)
formatDict(dicts, value) {
const dictData = this.getEnumsInfo(dicts, value);
if (dictData) {
return dictData.label || "";
}
return "";
},
// 获取字典数据(根据字典列表和字典值,获取指定字典数据)
getDictInfo(dicts, value) {
const dictDatas = dicts.filter(item => item.value === value);
if (dictDatas && dictDatas.length > 0) {
return dictDatas[0];
}
return null;
}
},
async created() {
// 如果 dict 不是 Dict 类型则请求字典
if (!(this.dict instanceof Dict)) {
return;
}
// 请求字典接口
await this.dict.init(this.$options.dicts);
}
})
}
3. 创建字典入口
在 dict 文件夹下创建index.js,如下
import dictMixin from "./dictMixin";
function install() {
Vue.use(dictMixin)
}
export default {
install
}
4. 安装字典
将 index.js 引入 main.js 然后使用 install 方法安装字典,如下
import dictMixin from "@/dict";
dictMixin.install();
5. 使用
在页面添加 dicts 属性,
export default {
name: "VueView",
dicts: ['status'], // 字典数组,可多个
data() {},
methods: {},
created() {}
}
然后页面就可以这样使用
1. 表格列翻译字典值
<el-table-column label="状态" align="center" prop="status">
<template scope="scope">
{{ formatDict(dict.type.status, scope.row.status) }}
</template>
</el-table-column>
2. 多选组件
<el-select v-model="form.status" placeholder="请选择状态" clearable size="small">
<el-option
v-for="d in dict.type.status"
:key="d.value"
:label="d.label"
:value="d.value"
/>
</el-select>
或
<el-radio-group v-model="form.status">
<el-radio
v-for="d in dict.type.status"
:label="d.value"
:key="d.value">
{{ enu.label }}
</el-radio>
</el-radio-group>