Assemblage of Enumerations in TypeScript

I am currently working with Vue.js, specifically dealing with Vue components. Within my codebase, I often find myself needing to compare values to an enum. While this works seamlessly in the script section of a .vue file, it poses a challenge in the HTML portion. For example:

<template>
    <v-app>
        {{MyEnum.EnumMemberOne}}
    </v-app>
</template>

This would trigger an error:

[Vue warn]: Property or method "MyEnum" is not defined on the instance but referenced during render...

To resolve this issue, I have to include the following in my script to access the enum:

import {MyEnum} from "@/types";

@Component({
    components: {}
})
export default class App extends Vue {
    myEnum = MyEnum;
}

Afterwards, I can simply reference the enum using myEnum in the HTML section. However, managing multiple enums and creating variables for each enum within every component becomes tedious.

Therefore, my goal is to establish a collection of enums that are readily available across all components, regardless of the number or specific usage of enums in each component.

In my types.ts file (where interfaces and enums are defined), I aim to achieve the following structure:

export enum MyEnum1 {
    EnumMemberOne,
    EnumMemberTwo,
}

export enum MyEnum2 {
    EnumMemberOne,
    EnumMemberTwo,
}

export interface EnumCollection {
    MyEnum1: MyEnum1;
    MyEnum2: MyEnum2;
}

This setup allows me to streamline the usage of enums in each component by simply including: enumCollection = EnumCollection;

Consequently, I can utilize the enums in the HTML section like this:

<template>
    <v-app>
        {{enumCollection.MyEnum1.EnumMemberOne}}
    </v-app>
</template>

Is this approach feasible? If not, what is a more effective way to consolidate all enums into one centralized location?

Answer №1

For my project, I needed a solution that involved having all enums in their own separate file. So, I created a Constants file to bring them all together:

In Constants.ts:

export * from '@/app/constants/MyEnum1';
export * from '@/app/constants/MyEnum2';
export * from '@/app/constants/MyEnum3';

In MyEnum1.ts, MyEnum2.ts, and so on:

export enum MyEnum1 {
    EnumMemberOne,
    EnumMemberTwo,
}

Within the main file:

import { createApp }       from 'vue';
import { App as VueApp }   from 'vue';
import * as constants      from '@/app/constants/Constants';

// ....

const vueApp:VueApp<Element> = createApp(AppVue);

vueApp.config.globalProperties.const = constants;

// ....

Now, you can easily access const.xxx in any template throughout your application:

<template>
    <v-app>
        {{const.MyEnum1.EnumMemberOne}}
    </v-app>
</template>

Note: The code above is specific to a Vue3 project, but a similar approach should also be applicable for Vue2.

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

Prisma allows for establishing one-to-many relationships with itself, enabling complex data connections

I am in the process of developing a simple app similar to Tinder using Prisma. In this app, users can swipe left or right to like or dislike other users. I want to be able to retrieve matches (users who also like me) and candidates (all users except myself ...

What is the best way to create an interactive experience with MapLibre GL in Full Screen mode?

Hello, I am seeking a solution to create a map with the interactive option set to false, but once in full screen mode, I need this parameter to be true. Do you have any suggestions or ideas on how to achieve this? const _map = new MapGL({ contai ...

The intersection observer is unable to track multiple references simultaneously

Hey there, I've been using a switch statement in my Next.js project to dynamically serve different components on a page. The switch statement processes a payload and determines which component to display based on that. These components are imported dy ...

Enable Intellisense for my custom ES6 JavaScript modules in VS Code

Using VS Code Intellisense can greatly enhance productivity when working with internal project files, providing helpful autocompletion features and utilizing written JSDoc comments. However, my current projects involve custom JavaScript libraries stored i ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

Troubleshooting: Issue with encoding in Javascript Blob using Ionic file plugin

Could you please help me troubleshoot why this code is not functioning correctly? Note: file is a native plugin var blob = new Blob(["This is the content of my blob"], { type: "text/plain" }); this.file.writeFile(this.file.dataDirectory, 'mylet ...

The function Keyboard.hide() is ineffective when used in a project built with capacitor or ionic 6

In my app, there is a simple form where users can input two values and have them added together. Below is the code for my form: <form (ngSubmit)="calculateTwo(value1, value2)"> <ion-grid> <ion-row> <ion-co ...

How can I adjust the font size of the placeholder text in an Angular

Here is an example of the input: <mat-form-field class="example-full-width" floatLabel="always"> <mat-label>Expedite Code</mat-label> <input type="string" placeholder="Expedite Code" [formControl]="expCode" matInput> </m ...

having difficulties entering text into the react input field

At the moment, my input field defaults to 1, but when I try to type something in it, nothing happens. interface Orders { order_graph_1: number; order_graph_2: number; } interface MyProps extends Orders { setOrders: (...args: any) => void; / ...

What is the best method for enabling browser zoom capabilities within playwright?

Is there a method to adjust the browser zoom level while running an end-to-end test? I attempted the following code without success. await page.keyboard.down('Control'); for (let i = 0; i < 7; i++) { await page.keyboard.press('+&apo ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

The array remains undefined even after being assigned within the subscribe function

I have encountered an issue in my Angular app where the array productLocations is being assigned in the ngOnInit method within a subscription, but it remains undefined when used in another method. Despite following advice on Stackoverflow to move the assig ...

Enable/Disable Text Editing Based on Vue Js Input

I’m working on a way to make certain parts of a string in an input editable or non-editable (readonly) depending on the context in Vue.js. For instance: I have this text: My Name is $John Doe$ Now, I want my Vue.js code to scan the string and allow edi ...

Transferring Information Between Vue Components

In my project, I have implemented 3 Vue components to work together seamlessly. Component A is responsible for listening to an event triggered by a user clicking on HTML text and storing the data into a variable. Component B utilizes this data to make an A ...

Displaying asynchronous data in a VueJS template

This is the current code snippet I am working with: <template> <div> <hot-table licenseKey='non-commercial-and-evaluation' :data="covertDataToTableReadable" colHeaders="true" width="600" height=& ...

Firing a function in Angular2 whenever an observable property undergoes a change

Utilizing a workingData service that stores crucial data across my application, it provides an observable to the Mock workingData object. @Injectable() export class WorkingDataService { getWorkingData(): Observable<WorkingData> { return Observ ...

Exploring how Angular mat-checkbox can be targeted within dynamically generated nested elements

I am facing a challenge with a series of checkboxes that I create using mat-checkbox, including a corresponding Select all checkbox. What I want to achieve is to selectively hide the specific (and first) checkbox without affecting any other elements within ...

Error encountered when trying to access an element referenced by v-if in the mounted callback of a

<template> <div> <transition name="fade" mode="out-in"> <div class="ui active inline loader" v-if="loading" key="loading"></div> <div v-else key="loaded"> <span class="foo" ref="foo">the ...

A guide on implementing a conditional useSelector to select a single variable depending on the parameter passed to the function

I am trying to create a single variable called selectorValue that can dynamically change based on the selector passed as a function parameter in the useSelector function. For instance, I need to be able to choose between the selector for physical books or ...

Order by surname in the alphabet

In what way can we organize the data from an array of objects alphabetically by last name when there is no separate property for first and last names, but rather a single property called fullname (see example data below)? If we were to sort the data by la ...