现实生活喜欢对称和轻微的时间错移。——博尔赫斯《南方》
填坑,官方文档:https://www.typescriptlang.org/docs/handbook/enums.html
我新建了一个vue
项目用来演示
这里代码如下:
1 2 3 4 5 6 7 8 9 10
| enum Direction { Up, Down, Left, Right } console.log({ Direction }); console.log({ 'Object.entries(Direction)': Object.entries(Direction) }); console.log({ 'Direction[0]': Direction[0] }); console.log({ 'Direction.Up': Direction.Up });
|
打印结果如下:

定义一个双向绑定的值
1
| const count = ref(Direction.Up)
|
在下方使用
1
| <button type="button" @click="count++">count is: {{ count + Direction[count] }}</button>
|
默认是0Up

点一下

这说明对枚举进行递增,等于对齐值进行递增
我们这里将枚举中定义字符串初始值
1 2 3 4 5 6
| enum Direction { Up = '上', Down = '下', Left = '左', Right = '右' }
|
然后发现之前生成的8
个属性变成了4
个,不支持直接使用值进行反向映射了


也无法自增了

但我们仍然可以使用这种方式

让其初始值变为1,后面的也会依次递增
比如这样写:
1 2 3 4 5 6
| enum Direction { Up = 1, Down, Left, Right = 10 }
|
生成的结果为:
1 2 3 4 5 6 7 8 9 10
| { "1": "Up", "2": "Down", "3": "Left", "10": "Right", "Up": 1, "Down": 2, "Left": 3, "Right": 10 }
|