vue3声明字段名为枚举类型
下面是Type的枚举声明,共有6个字段
enum Type {
? primary = "primary",
? success = "success",
? warning = "warning",
? warn = "warn", // warning alias
? danger = "danger",
? info = "info",
}
TypeScript 中声明类型的关键字有两个,interface 和 type,在声明 key 不确定类型的字段时稍有不同。
使用 type 进行声明:
type ColorConfig = {
? [key in Type]: Colors;
};
使用 interface 却只能像下面这样:
interface ColorConfig {
? [key: string]: Colors;
}
因为 interface 的索引只能是基础类型,类型别名也不可以。而 type 的索引可以是复合类型。
vue使用提升之"枚举"应用
方式一(适用于简易过滤器中)
// enum.js**文件
/**
?* 获取枚举值:STATUSMAP.TTT
?* 获取枚举描述:STATUSMAP.getDesc('SH')
?* 通过枚举值获取描述:STATUSMAP.getDescFromValue('TG')
?*/
let STATUSMAP = createEnum({
? SH: ['SH', '审核中'],
? TG: ['TG', '审核通过']
});
function createEnum(definition) {
? const valueMap = {};
? const descMap = {};
? for (const key of Object.keys(definition)) {
? ? const [value, desc] = definition[key];
? ? valueMap[key] = value;
? ? descMap[value] = desc;
? }
? return {
? ? ...valueMap,
? ? getDesc(key) {
? ? ? return (definition[key] && definition[key][1]) || '无';
? ? },
? ? getDescFromValue(value) {
? ? ? return descMap[value] || '无';
? ? }
? }
}
export default STATUSMAP;
view文件
<el-row>
? ?<el-button>枚举测试</el-button>
? ?<p>当前状态:{{STATUS.getDescFromValue('SH')}}</p>
? ?<p>也可用通过枚举名称获取描述:{{STATUS.getDesc('HHH')}}</p>
?</el-row>
?<!-- 过滤器中使用 则在filters过滤器中直接使用函数返回值 -->
方拾二(过滤器,循环列表)
// order.js文件
/**
?* 定义枚举值?
?*/
export default {
? order: [
? ? { value: 'TJ', label: '已提交' },
? ? { value: 'CZ', label: '处理中' },
? ? { value: 'CL', label: '已处理' },
? ],
? orderDetail: [
? ? { value: 'DF', label: '待发货' },
? ? { value: 'FH', label: '已发货' },
? ? { value: 'QS', label: '已签收' },
? ]
}
// constants.js文件
/**
* 定义枚举工具
* ?
*/
import order from './order/index.js';
let constants = {
? ...order
};
let valueMap = {};
let nameMap = {};
Object.keys(constants).forEach(key => {
? valueMap[key] = [];
? nameMap[key] = {};
? constants[key].forEach(event => {
? ? valueMap[key].push(event);
? ? nameMap[key][event.value] = event.label;
? });
});
export {
? valueMap,
? nameMap
}
/**
* view文件
*/
<template>
?? ?<h3>枚举值用于展示</h3>
?? ?<el-row>
?? ??? ?<el-button v-for="(item, index) in valueMap.order" :key="index">{{item.label}}</el-button>
?? ?</el-row>
?? ?<h3>枚举值过滤器</h3>
?? ?<el-row>
?? ??? ?<el-button>{{enumValue | filterStatus('orderDetail')}}</el-button>
?? ?</el-row>
</template>
<script>
?? ?import { valueMap, nameMap } from '@/constants';
?? ?export default {
?? ? ?data() {
?? ? ? ?return {
?? ? ? ? ?STATUS: STATUS,
?? ? ? ? ?valueMap,
?? ? ? ? ?enumValue: 'FH', // 发货
?? ? ? ?}
?? ? ?},
?? ? ?filters:{
?? ? ? ?filterStatus: function(val, key){
?? ? ? ? ?if(!val && val !== 0){
?? ? ? ? ? ?return '无';
?? ? ? ? ?}
?? ? ? ? ?return nameMap[key][val];?
?? ? ? ?}
?? ? ?}
?? ?}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于vue3声明字段名为枚举的类型详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did120884