1.概述
枚舉用于定義數(shù)據(jù)集合,使用枚舉可以定義一些帶名字的常量,有普通枚舉、字符串枚舉和常量枚舉等類型。
2.示例
- 普通枚舉:初始值默認(rèn)為 0,其余的屬性按順序依次遞增。
enum Color {
Red,
Blue,
Green
}
console.log(Color.Red); //0
// const red:Color=Color.Red;
// console.log(red);
復(fù)制代碼
也可手動(dòng)設(shè)置初始值(其余的屬性依舊按順序遞增):
enum Color {
Red=3,
Blue,
Green
}
console.log(Color.Red); //3
復(fù)制代碼
- 字符串枚舉:
enum Color {
Red='紅色',
Blue='藍(lán)色',
Green='綠色'
}
console.log(Color.Blue); //藍(lán)色
復(fù)制代碼
- 常量枚舉:使用 const 關(guān)鍵字修飾的枚舉
const enum Color {
Red,
Blue,
Green
}
console.log(Color.Red,Color.Blue,Color.Green); //0 1 2
復(fù)制代碼
3.枚舉的實(shí)際應(yīng)用
//enum.ts
/** 登錄狀態(tài) */
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>
復(fù)制代碼
可修改為:
//enum.ts
/** 登錄狀態(tài) */
export enum LoginStatus { //中文的字符串枚舉
'登錄',
'注冊(cè)',
}
//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>
復(fù)制代碼
英文的普通枚舉
只有一種作用:只能通過(guò)數(shù)組下標(biāo)讀出枚舉里的屬性,不便于代碼的理解。
LoginStatus[0]---'Login'
中文的字符串枚舉
有兩種作用:
1.當(dāng)用中文形式時(shí),可以顯示出對(duì)象屬性的索引。LoginStatus['登錄']---0
2.當(dāng)用數(shù)組下標(biāo)形式時(shí),可以顯示出中文,以便提高代碼的可讀性與理解。LoginStatus[0]---登錄文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-602240.html
所以,項(xiàng)目中建議使用中文的字符串枚舉。
參考:https://juejin.cn/post/7137982601481945102
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-602240.html
到了這里,關(guān)于TS—枚舉Enum用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!