Search code examples
javascripthtmltypescriptvue.jsinterpolation

How to add and insert enum text values into Vue project HTML?


I have an enum called MaritalStatus:

enum MaritalStatus {
  Single,
  Heartbroken,
  Married,
}

And an array of objects which incorporates that enum (This is a typescript project btw):

const contacts: Contact[] = [
  {
    id: 1,
    name: "Tony",
    age: 18,
    maritalStatus: MaritalStatus.Heartbroken,
    dateOfBirth: new Date(2006, 1, 2),
    occupation: "Software Engineer",
  },
  {etc.}
]

Here is the only part of my HTML that matters:

<div
  v-for="contact in contacts"
  :key="contact.id"
>
  <span class="my-2">{{ contact.maritalStatus }}</span>
</div>

When this displays, I get a list of names, with numbers 0-2 displaying below them. Obviously what I want to display is the text "Single", "Married", or "Heartbroken".

How do I go about this? Thanks!


Solution

  • That is because typescript will automatically assign auto-incrementing numerical values to your enum keys under the hood. You have 2 options:

    Use value assignment:

    enum MaritalStatus {
        Single = "Single",
        Heartbroken = "Heartbroken".
        Married = "Married"
    }
    

    Or access the value using an index accessor:

    martialStatus: MaritalStatus[MaritalStatus.Heartbroken]