背景
当我们在编写前端代码时,往往会对状态类的字段感到苦恼,因为他可能是0,1,2…,也可能是…,我们将他称之为:“字典(dict)”。它是多变的,而且后期可能会有所改动,所以我们不可能把在前端写死。
处理方法其实有很多种,可以让后端来处理,返回时进行翻译,这可能降低了灵活性,我们也可以前端处理,下面我们来讲解一下前端的一种处理方法。
原理:全局使用Vue的混入(mixin),来实现页面创建时进行请求后端字典列表,然后在页面通过该列表进行翻译字典。
首先创建一个 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);
}
}
}
创建 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);
}
})
}
在 dict 文件夹下创建index.js,如下
import dictMixin from "./dictMixin";
function install() {
Vue.use(dictMixin)
}
export default {
install
}
将 index.js 引入 main.js 然后使用 install 方法安装字典,如下
import dictMixin from "@/dict";
dictMixin.install();
在页面添加 dicts 属性,
export default {
name: "VueView",
dicts: ['status'], // 字典数组,可多个
data() {},
methods: {},
created() {}
}
然后页面就可以这样使用
{{ formatDict(dict.type.status, scope.row.status) }}
或
{{ enu.label }}