在 Vue 项目中添加字典翻译工具

背景
当我们在编写前端代码时,往往会对状态类的字段感到苦恼,因为他可能是0,1,2…,也可能是…,我们将他称之为:“字典(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="状态" 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>
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会功夫的李白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值