VUE中自定义枚举类

在一般的业务里面,都会涉及到表格,列表中放着一个按钮有不同颜色或者是不同状态,在一般的情况下,使用vue语法中的v-if或者三元表达式去实现类似的效果。这里将自定义枚举类,减少v-if的使用。

1、定义枚举类

在项目的utils中新建一个文件Enum.js,在里面复制一下代码

/**
 * 枚举类
 *
 * @param props  [{key: number|string, value: number|string, ...other}]
 * @example
 *  const StepEnum = new Enum([
 *    { key: 'STEP1', name: '步骤1', value: 1 },
 *    { key: 'SETP2', name: '步骤2', value: 2 },
 *  ]);
 *
 * @class Enum
 *
 * @method get(value) 通过value获取当前列的值
 *                    return { key: 'SETP2', name: '步骤2', value: 2 }
 *
 * @returns {key1: number|string, key2: number|string}
 * {
 *   CREATE: 1,
 *   APPROVED: 2,
 * }
 */
export default class Enum {
  /**
   * 初始化
   * @param {Array} props []
   */
  constructor(props = []) {
    this.__props = {};
    if (props.length) {
      props.forEach((element) => {
        if (element.key && element.value) {
          this[element.key] = element.value;
          this.__props[element.value] = element;
        } else {
          console.error(element + "Enum缺少必要的key或value");
        }
      });
    }
  }

  /**
   * 根据 value 获取对象值
   * @param {string|number} value 状态值
   */
  get(value) {
    return this.__props[value];
  }

  /**
   * 获取枚举数组
   */
  getArray() {
    const arr = [];
    for (const key in this.__props) {
      if (Object.prototype.hasOwnProperty.call(this.__props, key)) {
        arr.push(this.__props[key]);
      }
    }
    return arr;
  }
}

2、使用枚举类,枚举相关数据

在项目中新建一个目录enums,然后在目录中添加index.js文件,统一导出所有的枚举文件,然后再创建自己的枚举文件。这里我创建的是OderStatus.js文件

import Enum from "@/utils/Enum";

export default new Enum([
  { key: "0", value: 1, name: "待付款", color: "#fe9e3d" },
  { key: "1", value: 2, name: "待审核", color: "#000000" },
  { key: "2", value: 3, name: "待发货", color: "#fe9e3d" },
  { key: "3", value: 4, name: "已发货", color: "#64d4cc" },
  { key: "4", value: 5, name: "已完成", color: "#89898a" },
  { key: "5", value: 6, name: "已关闭", color: "#89898a" },
]);

然后再index,js文件中添加代码

export { default as OrderStatusEnum } from "./OrderStatus.js";

3、组件中使用自定义枚举类

在自己对应的组件中引入定义好的枚举文件

import { OrderStatusEnum } from "../../enums/index";

组件中使用

<div class="text-bd" :style="getColor(item.orderStatus)">
    {{OrderStatusEnum.get(item.orderStatus).name}}
</div>

实现效果,这里简单枚举了6个状态,在更复杂的业务里面,可能会有更多的类型。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值