vue v-for of typescript enum
Answer a question Why does this v-for loop over an enum show the names and values? How can I iterate only over the keys? export enum Colors { "RED" = 1, "BLUE" = 2, "GREEN" = 3, } <template> <div> <v-
Answer a question
Why does this v-for
loop over an enum
show the names and values?
How can I iterate only over the keys?
export enum Colors {
"RED" = 1,
"BLUE" = 2,
"GREEN" = 3,
}
<template>
<div>
<v-chip v-for="key in Colors" :key="key">{{key}}</v-chip>
</div>
</template>
<script lang="ts">
import {Colors} from "./Enums"
import Vue from "vue";
export default Vue.extend({
data: () => ({
Colors,
}),
});
</script>
This strangely results in 6 chips, but I would expect only 3.
- RED
- BLUE
- GREEN
- 1
- 2
- 3
Answers
Because v-for
lists all properties of an object, it will show both the forward and reverse properties of the Typescript enum. You'll need to filter the keys yourself, possibly using Number.isInteger().
For context, Typescript enums get reverse mappings by default:
In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names. For example, in this example:
enum Enum { A, } let a = Enum.A; let nameOfA = Enum[a]; // "A"
TypeScript compiles this down to the following JavaScript:
"use strict"; var Enum; (function (Enum) { Enum[Enum["A"] = 0] = "A"; })(Enum || (Enum = {})); let a = Enum.A; let nameOfA = Enum[a]; // "A"
In this generated code, an enum is compiled into an object that stores both forward (
name -> value
) and reverse (value -> name
) mappings. References to other enum members are always emitted as property accesses and never inlined.
更多推荐
所有评论(0)