Definition of enum across components

Viewed 1861

I am developing with Vue.js 3.0 and TypeScript.
I want to define an enum to be used in multiple components.
How and where should I write in the file?

Directory

src/
├ components/
│ ├ ParentComponent.vue
│ └ ChildComponent.vue
└ App.vue

ChildComponent.vue

<template>
  <p>{{ color }}</p>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'

enum Color {
  red = 1,
  blue
}

export default defineComponent({
  props: {
    color: { type: Color, required: true }
  }
})
</script>

ParentComponent.vue

<template>
  <div>
    <ChildComponent
      :color="state.color"
    />
  </div>
</template>

<script lang="ts">
import ChildComponent from './ChildComponent.vue'
import { defineComponent, reactive } from 'vue'

// duplicate
enum Color {
  red = 1,
  blue
}

interface State {
  color: Color
}

export default defineComponent({
  components: {
    ChildComponent
  },
  setup () {
    const state = reactive<State>({
      color: Color.red
    })
    return { state }
  }
})
</script>
1 Answers

You can define & export the enum in a separate file, and import it in different files to use it. Where do you put this file depends on you mainly, how you want to structure your project.

For example, a types.ts file in the src folder can define and export the enum like:

export enum Color {
    red = 1,
    blue = 2
}

And you can use the enum anywhere by importing it like:

import { Color } from '@/types';

This is assuming that you've aliased the src folder to @ in your TypeScript configuration available in tsconfig.json file.

Related