Iterating through typescript enums in Vue using v-for

Why is the v-for loop over an enum displaying both names and values?

Is there a way to 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>

The current behavior results in 6 chips, while I expected only 3.

  • RED
  • BLUE
  • GREEN
  • 1
  • 2
  • 3

Answer №1

As v-for iterates through all properties of an object, it will display both the forward and reverse properties of the Typescript enum. To only show specific keys, you may need to manually filter the keys, potentially using Number.isInteger().

To provide some background, Typescript enums inherently include 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 scenario:

enum Enum {
  A,
}

let a = Enum.A;
let nameOfA = Enum[a]; // "A"

TypeScript translates this into the following JavaScript code:

"use strict";
var Enum;
(function (Enum) {
  Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

In this resultant code snippet, an enum is compiled into an object that saves both forward (name -> value) and reverse (value -> name) mappings. Any references to other enum members are always output as property accesses rather than inline.

Answer №2

Using Jeff's guidance, the final code snippet will resemble the one below:

<template>
    <div>
      <v-chip 
        v-for="([value, key], idx) in Object.entries(Colors).filter(([_, k]) => Number.isInteger(k))" 
        :key="idx"
      >
        {{ key }}
      </v-chip>
    </div>
</template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for detecting an empty Vuex store state and triggering a computed property when it's first initialized

I am currently developing a project using Vue Storefront along with Vuex. One of the key functionalities I am working on is how to sort products in my online store. Here is the code snippet for the sorting element: <SfSelect class="n ...

Trouble with Webpack alias functionality observed during deployment on Heroku

After setting up a demo app for a library project at my company, I successfully deployed it to Heroku using Vue CLI with webpack and node integration. Recently, I realized the necessity of generating a translations file post-build. To achieve this, I incor ...

Communicating Progress Updates from C# to Angular 6 Using HttpPost

I'm building an Angular 6 application with a progress bar that displays the rendering and downloading progress of a PDF file as a percentage. Here's my Post call: renderReport(renderObjectId: number): Observable<HttpEvent<Blob>> { ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

TypeScript code runs smoothly on local environment, however encounters issues when deployed to production

<div> <div style="text-align:center"> <button class="btnClass">{{ submitButtonCaption }}</button> <button type="button" style="margin-left:15px;" class="cancelButton" (click)="clearSearch()"> {{ clearButtonCapt ...

Is it possible for an object's property specified in a TypeScript interface to also incorporate the interface within its own declaration?

While it may seem like an unusual request, in my specific scenario, it would be a perfect fit. I am working with an object named layer that looks something like this: const layer = { Title: 'parent title', Name: 'parent name', ...

Error TS2322: Cannot assign a variable of type 'number' to a variable of type 'string'

Encountered an issue with TS2322 error while attempting to compile my Angular application. The error occurs when using a variable [link] that represents the index number. When declaring this variable, I use: @Input() link!: string; This link is used as ...

Number as the Key in Typescript Record<number, string> is allowed

As a newcomer to TypeScript, I am still learning a lot and came across this code snippet that involves the Record utility types, which is quite perplexing for me. The code functions correctly in the playground environment. const data = async (name: string ...

Remove a key using Vue Resource

I am looking to remove a specific piece of data from my firebase database using its key: https://i.stack.imgur.com/S1zDA.png This is the approach I have tried in order to delete all data from the database: this.$http.delete('data.json', book.i ...

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

A guide on successfully implementing Nuxt-img on nuxt3 generate!

I've been experimenting with nuxt-image on NUXT3, but I've run into an issue when using the generate command. While images display correctly during development, they return a 404 error when using nuxt generate. In my nuxt config, I have: modules ...

Tips for enforcing a mandatory type with TypeScript

Creating a custom type called InputType with optional properties like this: export type InputType = { configJsonUrl?: string; configJsObject?: DataType; rawData?: { [key: string]: string }; action?: () => void; }; export type DataType = { id ...

Having trouble displaying options in VueJS Component using datalist

Currently, I am harnessing the power of VueJS and its components to create an extensive array of datalists and selectors, each equipped with a submit button for validation upon form submission. Initially, I successfully implemented a datalist within a com ...

Creating computed properties dynamically in Vue after initialization

Is it feasible to generate a computed property dynamically after the component is initialized? I do not have prior knowledge of what name the computed property should be assigned. ...

Loop through the tabs in a for loop until reaching the specified length

I have a switch case function inside a modal in Vue. My goal is to create tabs or screens for different components. <div v-switch="tabnumber"> <div v-case="1"> <form-component> ...

Guide on integrating Vue JS code into a .Net MVC project

I am facing a challenge when trying to integrate a Vue JS folder containing index.html, main.css, main.js, and vue.js into a .Net MVC project. I have limited knowledge about .Net and how it functions, but I understand where the CSS files need to go in the ...

Obtaining the category value within a slot of the Vuetify calendar

I am struggling to implement hover functionality in the categories view of Vuetify calendar within the body section (slot day-body). When I try to add hover functionality, the entire row ends up being affected by the hover effect, even though I only want i ...

My VUE JS Application is displaying outdated images that have been saved in the cache

I encountered a perplexing issue with my Vue application pertaining to user profiles and timelines. Specifically, within the user profile, there are four pictures that can be uploaded or deleted. The problem arises when updating these pictures; sometimes t ...

Optimizing your data layer in Angular2: A Guide to Best Practices

As a newcomer to Angular2, I am diving into hands-on learning. My current project involves building multiple views with parent components, child components, and database services. After successfully creating one view, I am now gearing up to implement other ...

Global Vue Component Styles Seeping Through Entire Website Interface

By "Leaking", I mean the following scenario. I have an About.vue file with its own styling (About.scss) and endpoint "/about". Additionally, I have the home page endpoint "/" and its corresponding Laravel blade template (Index.blade.php) with its own styli ...