接做网站的,重庆装修公司排名表,wordpress防sql注入,51网站一起做网店背景 当我们在编写前端代码时#xff0c;往往会对状态类的字段感到苦恼#xff0c;因为他可能是0#xff0c;1#xff0c;2…#xff0c;也可能是…#xff0c;我们将他称之为#xff1a;“字典#xff08;dict#xff09;”。它是多变的#xff0c;而且后期可能会有… 背景 当我们在编写前端代码时往往会对状态类的字段感到苦恼因为他可能是012…也可能是…我们将他称之为“字典dict”。它是多变的而且后期可能会有所改动所以我们不可能把在前端写死。 处理方法其实有很多种可以让后端来处理返回时进行翻译这可能降低了灵活性我们也可以前端处理下面我们来讲解一下前端的一种处理方法。 原理全局使用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状态 aligncenter propstatustemplate scopescope{{ formatDict(dict.type.status, scope.row.status) }}/template
/el-table-column2. 多选组件
el-select v-modelform.status placeholder请选择状态 clearable sizesmallel-optionv-ford in dict.type.status:keyd.value:labeld.label:valued.value/
/el-select或
el-radio-group v-modelform.statusel-radiov-ford in dict.type.status:labeld.value:keyd.value{{ enu.label }}/el-radio
/el-radio-group