Navigating global variables and functions in Vue3 with TypeScript

Feeling lost in the world of Vue.js, seeking guidance here.

Attempting to handle global data and its corresponding functions has led me on a journey. Initially, I experimented with declaring a global variable. But as more functions came into play, I transitioned to creating a class that encapsulates both data and functions, marking them as static. The data gets initialized within the constructor of this class using Axios get method. To access this object like a singleton instance, it was then declared within the setup() function of App.vue.

<Common.ts>


        export class DataManager {
            static datas: DataInfo[];
            
            constructor() {
                axios.get("api").then((res) => {
                    for(const eachData of res.data) {
                        DataManager.datas.push({
                            id: eachData.id,
                            name: eachData.name,
                        })
                    }
                ).catch(error -> {
                    console.log(error)
                }
            }
        
            static getDataName(id: number) : string {
                const foundInfo = DataManager.datas.find((element : DataInfo) => {
                    return element.id === id;
                })
                if(foundInfo === undefined) {
                    return ""
                }
                return foundInfo.name;
            }
        }
    

<App.vue>

  
                  setup() {
                    const SingletonDataManager = new DataManager();
                    
                    return {
                        SingletonDataManager
                    }
                 }

Seeking validation on whether this approach is ideal or are there better alternatives for managing global variables and functions? If using a singleton pattern is appropriate, perhaps sharing the singleton object without utilizing static methods through provide/Inject could be advantageous... thoughts?

UPDATE incorporating composable composition:


                  const datas = ref([] as DataInfo[])
                  
                  axios.get("api").then((res) => {
                      for(const eachData of res.data) {
                          Object.assign(datas.value, eachData)
                      }
                  ).catch(error -> {
                      console.log(error)
                  }
                  
                  export function useDataManager() {
                      const getDataName = (id: number) => {
                          return blahblah
                      }
                      
                      return {
                          datas,
                          getDataName,
                      }
                  }
            

Answer №1

This is a great example of how to use composables in Vue.js

Check out this simple implementation:

<script setup>
// UserData.vue
import { UseUserData } from './UserData'

const userData = UseUserData()
</script>

<template>{{ userData.getUserName() }}</template>
// UserData.ts

const userData = new UserData();
export function UseUserData(){
  return userData;
}

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

JavaScript format nested data structure

For my latest project, I am working on a blog using Strapi combined with Nuxt. To fetch the categories and articles data for my blog, I send a JSON object from my front-end application using Axios. { "data": [ { "id": 1, ...

How to minimize xAxes labels in Chart.js

As a newcomer to Chart.js, I am encountering some challenges. My goal is to create a bar chart that displays hourly information. However, when attempting to show data for a week, a month, or an extended period, I face issues with reducing the labels on the ...

Experience inadequate test coverage while conducting unit tests in Vue.js

I'm currently working on Vuejs unit testing using karma+mocha+chai+webpack and aiming to achieve code coverage with istanbul. However, I've encountered an issue where importing certain utility functions or components into the component being tes ...

Tips for exporting and reusing third-party types in TypeScript

I am facing a challenge with my package, which relies on a 3rd party package API for most of its functions. How can I export the types from the 3rd party package API in my own package? For instance: React uses @types/react to define its types Let's ...

VueJS: The current date is before today's date when using Date.now

I am currently comparing two dates in order to perform a filtered search. My goal is to only include objects in the filtered results if the date is after today, excluding any objects dated for today. However, when I run my code, it appears that items wit ...

Attempting to limit entry to a pathway when the loggedIn criterion is satisfied

I am currently facing a challenge with restricting access to the login page if the user is already logged in. I have been attempting to achieve this by checking for an existing token in the localStorage. Do you have any suggestions on how I can troublesh ...

Comparing Passport-azure-ad with OAuth 2.0 Authorization code flow (with PKCE) in VueJS SPA with Vuex

After extensive research, I am currently exploring the ideal pattern that aligns with my requirements. Here's what tools and technologies I am currently utilizing: https://learn.microsoft.com/en-us/azure/active-directory/develop/sample-v2-code VueJS ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Looping issue with ForEach in Typscript with Firebase Functions

While browsing through various questions on this topic, I've noticed that the specific answers provided don't quite fit my situation. My query involves converting a Google Firebase RTB datasnapshot into an array of custom objects, each representi ...

Dealing with Unexpected Timeout Errors and Memory Leaks in Express/Typescript Using Jest, Supertest, and TypeORM

Currently, I am in the process of writing unit tests for an express API. Each test suite initiates a fresh instance of an express server before running the tests. Individually, each test suite runs smoothly without any problems. However, when executed tog ...

Creating a TypeScript client using NSwag with named properties: A step-by-step guide

Our TypeScript client is created from a swagger interface using NSwag. The resulting client code typically looks like this: client.EndPointFoo(arg1, arg2, arg3, ...) However, we encounter issues when NSwag changes the order of arguments in response to mo ...

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

Vue's watch feature will not execute if the watched property remains unchanged during a page reload

<template> <!-- The navbar has a property for gender, the color of the navbar will change depending on the gender --> <!-- pass the props gender through a form submission and event --> <div class="nav-main" :class="{f ...

Nested formArrays within formArrays in Angular 4

I've been working on implementing a FormArray inside another FormArray, but it doesn't seem to be functioning correctly. I also tried the solution provided in the link below, but it didn't work for me. How to get FormArrayName when the Form ...

Best practices for managing login authentication using MongoDB in a RESTful API

I'm currently figuring out how to verify if the values align with the MongoDB data. In my approach, I'm utilizing the PUT method along with attempting to utilize findOneAndUpdate to validate the values. <script> const logindetails = new Vu ...

What is the reason for TypeScript's refusal to accept this task?

In my attempt to create a type that can be A, B, or an object with a key containing an array of 2 or more items that are either A, B, or another similar object (thus allowing for recursive definition). This is the solution I came up with: type A = { p ...

**Finding the Index of a Table Row in Vue-Tables-2**

Recently, I came across some vue code that utilizes vue-tables-2. The table in question is quite simple and looks like this... <v-client-table :data="myRows" :columns="columns" :options="options"> <div slot=" ...

What is the best way to configure multiple keys for components within a template tag using v-for?

In my attempt to render a list using v-for, I encountered an issue. The documentation provided clear examples for most use cases, but I couldn't figure out how to properly set keys for multiple custom components within one v-for loop. <template v- ...

When Nuxt is deployed to Netlify, the CSS Opacity is incorrectly compiled at 1% instead of the intended 100%

I've encountered an issue with my Nuxt app when deploying it to Netlify. After running yarn generate automatically, I noticed some strange CSS behavior in production. Specifically, there is a hover effect on a card that seems to be working fine local ...

Learn how to reference a parameter within the meta title of a route in Vue.js

I'm encountering an issue when attempting to call a parameter in the meta title route, I've already attempted this method but it's still not working { path: '/test/blog/:slug', name: 'Surah', component: Surah ...