Tips for Allowing Multiple Exports in a Vue 3 Single File Component

I am currently working on a Vue3 Single File Component for a customized list. Within this single file component, my objective is to export the main default Vue component along with an enum that declares the type of list it represents:

child:

<template>
  <Listbox>
    <template #header>
      <h5>{{listType}}</h5>
    </template>
  </Listbox>
</template>

<script lang="ts">
export enum PagesListType {
  RecentlyCreated = 'Recently Created',
  RecentlyModified = 'Recently Modified',
  Starred = 'Starred'
};

export default {
  props: {
    listType: PagesListType
  },
  data() {
    return {
      pages: [],
      PagesListType
    };
  },
};

</script>

The enum specifically pertains to the functionality of this particular component and doesn't need to be placed in a different types folder. It directly influences how this list functions. However, encounters issues when attempting to do so within the parent component:

parent:

<template>
  <div>
    <PagesList :listType="PagesListType.RecentlyCreated"></PagesList>
    <PagesList :listType="PagesListType.RecentlyModified"></PagesList>
    <PagesList :listType="PagesListType.Starred"></PagesList>
  </div>
</template>

<script lang="ts">
import PagesList, { PagesListType } from './PagesList.vue';

export default {
  //details of the parent component
};
</script>

Upon importing the named PagesListType enum, it appears as undefined. What steps should I take to correctly export the named enum? Thank you!

Answer №1

It is my belief that separating the enum into its own file and importing it in various files for use is a good practice. The location of this file can be determined based on how you wish to organize your project.

For example, you can create a file named types.ts within the src folder to define and export the enum as follows:

export enum PagesListType {
  RecentlyCreated = 'Recently Created',
  RecentlyModified = 'Recently Modified',
  Starred = 'Starred'
}

You can then import and use the enum anywhere in your code like this:

import { PagesListType } from '@/types';

Make sure to use @/ instead of src/ when importing due to the configuration set in your TypeScript file (tsconfig.json) where src is mapped to @.

Answer №2

I managed to make this work by adjusting the way I exported the enum, integrating it as a property within the default component export:

child:

enum PagesListType {
  RecentlyCreated = 'Recently Created',
  RecentlyModified = 'Recently Modified',
  Starred = 'Starred'
};

export default {
  props: {
    listType: PagesListType
  },
  PagesListType,
  data() {
    return {
      pages: [],
      PagesListType
    };
  },
};

parent:

<template>
  <div>
    <PagesList :listType="created"></PagesList>
    <PagesList :listType="modified"></PagesList>
    <PagesList :listType="starred"></PagesList>
  </div>
</template>

<script lang="ts">
import PagesList from './PagesList.vue';

export default {
  computed: {
    created() {
      return PagesList.PagesListType.RecentlyCreated;
    },
    modified() {
      return PagesList.PagesListType.RecentlyModified;
    },
    starred() {
      return PagesList.PagesListType.Starred;
    }
  },
//other parent implementation details omitted
};
</script>

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

Recursive functions that request input from the user

Currently in the process of developing a fun little script to help me organize and rate the movies in my personal collection. Among my list are a number of different movie titles that desperately need to be organized. The plan is to implement a merge-sort- ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

Error encountered in jQueryUI Autocomplete: the function 'this.source' is not defined

I have been working on incorporating a live search feature that scans through keys in a JSON obtained from a public API. To achieve this, I am utilizing Jquery UI. However, I encountered the following error and I am uncertain about how to resolve it. Un ...

Storing and Manipulating a JavaScript Object with Vuex: A New Perspective

Consider a hypothetical JavaScript object class like this: class Car { var engineTurnedOn = false; ... public turnEngineOn() { engineTurnedOn = true } } If I want to turn the engine on, should I create an action called 'turnEngineOn&ap ...

Securing your folders with Next Auth middleware

I am currently developing a NextJS application and have implemented routers at pages/dashboard/* that I need to secure. My goal is to restrict access to these routes only to authenticated users. I am utilizing Prisma for data management, with Google as the ...

What is the best way to display a div based on a keyword match?

If the keyword search results in a match, I can display the corresponding input text and its related category div. Now, I am attempting to also search through category names. If the searched keyword matches a category name, that specific div should be visi ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...

Calculate the unique UV coordinates for a custom Buffer Geometry in THREE.JS

I am currently working on creating a curved wall using a vertices array in three JS. The array contains some base vertices in 2D which represent the bottom vertices of the wall. These vertices include the center, lower, and upper points, making it a two-fa ...

What is the best way to convert an ajax get request into a post request using jQuery?

I'm interested in transforming a GET request to a POST request: $.ajax({ url: '/items?ids=' + value.join(','), method: 'get', dataType: 'json' }) What changes do I need to make to turn this into a ...

JavaScript concatenation of arrays

I am working with two arrays: let num1 = [[1]]; const num2 = [2, [3]]; When I combine these arrays, I create a new array: const numbers = num1.concat(num2); console.log(numbers); // This will result in [[1], 2, [3]] Next, I add a ne ...

Prevent the Stop Button from triggering submission and then utilize JavaScript to submit the form

I have a global delete button utilized in various sections of my site. Below is the code snippet for reference. public function delete_button($id_to_be_deleted, $form_to_post_to, $button_name){ return form_open($form_to_post_to, array('class&apos ...

A sophisticated method for dynamically expanding a text input field as characters are being typed

I recently came across a tutorial on how to make input type text auto-expand while also setting a specific width expand, which I found quite helpful. However, upon implementation, I noticed a few issues that need to be addressed: When typing in capital l ...

How can you utilize positioning and margins with Flexboxes?

<template> <div class="flex justify-center"> <div class="h-px-500 md:w-1/6 bg-orange-200 text-center">1</div> <div class="h-px-500 md:w-1/6 bg-orange-300 text-center">2</div> <div class="h-px-500 md:w-1/ ...

Angular Redirect Function: An Overview

In the Angular project I'm working on, there is a function that should navigate to the home when executed. Within this function, there is a condition where if true, it should redirect somewhere. if (condition) { location.url('/home') ...

Help needed with using Regex to restrict the number of alphabetical characters allowed

Struggling with configuring RegEx's. Seeking guidance to create a RegEx with the following criteria: Only allow numbers (0-9) Allow a period (.), negative sign (-), plus sign (+), dollar sign ($), and comma (,) Do not permit any alphabetic characte ...

Implementing jQuery form validation including checking for the strength of the password

My understanding of jQuery was quite basic until I began working on jQuery form validation with password strength check. I successfully completed the password strength check portion, but now I am unsure of how to enable the submit button once the condition ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

Is it recommended to incorporate router.isReady when making requests with react-query?

Struggling with incorporating react-query into my codebase, currently using getStaticProps. Experimenting with router.isReady from next/router to ensure the page waits for router.query value before passing it as props to the react hook. Take a look at my ...

Expanding the Number of Arguments Sent to a Callback Function

I have a scenario where I am using a method that sends a POST request and then triggers a specific callback function to manage the response: myService.verify(id, verificationCallback); function verificationCallback(err, response) { ... } My query is two ...

How can I enter a single backslash for location input in node.js without using double backslashes?

I have a project where the user needs to input a word to search for in files along with the folder location. However, I am struggling to write code that allows the user to input the location using single backslashes instead of double backslashes. const fol ...