欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

TS 枚举枚举用法

最编程 2024-04-22 10:29:44
...

1.概述

枚举用于定义数据集合,使用枚举可以定义一些带名字的常量,有普通枚举、字符串枚举和常量枚举等类型。

2.示例

  • 普通枚举:初始值默认为 0,其余的属性按顺序依次递增。
enum Color {
    Red,
    Blue,
    Green
} 
console.log(Color.Red);  //0
// const red:Color=Color.Red;
// console.log(red); 

也可手动设置初始值(其余的属性依旧按顺序递增):

enum Color {
    Red=3,
    Blue,
    Green
}
console.log(Color.Red);  //3
  • 字符串枚举:
enum Color {     
    Red='红色',
    Blue='蓝色',
    Green='绿色'
}
console.log(Color.Blue);  //蓝色
  • 常量枚举:使用 const 关键字修饰的枚举
const enum Color {
    Red,
    Blue,
    Green
}
console.log(Color.Red,Color.Blue,Color.Green);  //0 1 2

3.枚举的实际应用

//enum.ts
/** 登录状态 */
export enum LoginStatus {  //普通枚举
  Login,
  Register,
}
//LoginStatus[0]---'Login'

//index.vue
<template>
      <el-button color="#4A52FF" class="w-284px h-54px rounded-6px text-20px font-light" type="primary"
        @click="userLogin">
        登录
      </el-button>
</template>

<script setup lang='ts'>
import { LoginStatus } from '~/types';
</script>

可修改为:

//enum.ts
/** 登录状态 */
export enum LoginStatus {   //中文的字符串枚举
  '登录',
  '注册',
}
//LoginStatus['登录']---0
//LoginStatus[0]---登录

//index.vue
<template>
      <el-button color="#4A52FF" class="w-284px h-54px rounded-6px text-20px font-light" type="primary"
        @click="userLogin">
        {{ LoginStatus[0] }}   //登录
      </el-button>
</template>

<script setup lang='ts'>
import { LoginStatus } from '~/types';
</script>

英文的普通枚举只有一种作用:只能通过数组下标读出枚举里的属性,不便于代码的理解。

LoginStatus[0]---'Login'

中文的字符串枚举有两种作用:

1.当用中文形式时,可以显示出对象属性的索引。LoginStatus['登录']---0

2.当用数组下标形式时,可以显示出中文,以便提高代码的可读性与理解。LoginStatus[0]---登录

所以,项目中建议使用中文的字符串枚举。