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

When attempting to pass an array of objects to a child component, TypeScript raises an error regarding types

Hey everyone, I'm currently facing an issue while trying to pass an array of objects as props. Here's the content of my data.json file: [ { "category": "Reaction", "score": 80, "icon": " ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

Encountering a VueJS error when trying to locate a module while using a JSON file

I've been tasked with finding a solution to dynamically import pages within vuejs projects that are being built with a CLI tool by my team. I initially attempted to use functions as a string ("() => import(...)") and then evaluate that string, but ...

Implementing dynamic option selection in Vue using JavaScript and v-model

Is there a way to manage the chosen value in a v-modeled select tag using vue.js? I created a jsFiddle demonstration, but unfortunately, it is not functioning correctly. This leads to my inquiry: vm.$set('selected', '1') // does not wo ...

Vue.js and Vuetify are showing an error message for an unknown custom element: [ ... ]. Have you properly registered the component?

I keep encountering this issue with every HTML tag from Vuetify. I added Vuetify to my project by running npm install --save-dev vuetify In the main.js file, I have the following code: const Vue = require("vue"); const Vuetify = require("vuetify"); cons ...

Why using $refs in interpolation fails and leads to errors in Vue.js 2.x components

Here is a codepen I created: codepen const sidebar = { name: "sidebar", template: "<p>SIDEBAR</p>", data() { return { active: true }; }, methods: { test() { alert("test: " + this.active) } } }; new Vue ...

How can you obtain the user ID by verifying an email when using applyActionCode in Firebase 9 modular?

Is there a way to access the UID of an email verified user? Will the response provide any helpful insights, or should I handle this from another source? const handleVerifyEmail = (auth: any, actionCode: any) => { applyActionCode(auth, actionCode! ...

Encountering a Laravel Vue issue while attempting to implement chart.js using the Laravel-charts package

While utilizing Laravel charts from , I encountered an error message below. I observed that the error vanishes when I remove this particular line (which is associated with rendering and placed in the layout before yielding content). However, upon doing so ...

Unable to retrieve the accurate scrollHeight value for a textarea in VueJs and Vuetify

Trying to access the scrollHeight value of a textarea field, I encountered an issue when using the document object: document.querySelector("#textarea-element").scrollHeight. The value returned was correct. However, when attempting to retrieve it using refs ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

I am looking for assistance constructing a task management application using vue.js

I am facing an issue with developing a to-do list using Vue.js. The goal is to add tasks to the list by entering them and clicking a button. Once added, the new task should show up under "All Tasks" and "Not finished". Buttons for marking tasks as " ...

Troubleshooting navigation menu problem in Nuxt/Vue caused by compatibility issues with WP API V

Currently, I am in the process of constructing a website using Nuxt paired with headless WordPress. All the necessary data is being acquired from the WordPress API (wp-json). My main concern at the moment lies within the navigation menu, particularly with ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

The challenge of validating in Typescript and utilizing type inference

I am currently facing an issue with a function that resembles the one provided below (I have created a simplified example for discussion purposes): interface Variable { someMethod: () => void } const validateVariable(variable: Variable | undefined) { ...

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

Unlocking the capabilities of Chrome extensions using Angular 2 and TypeScript

Currently attempting to develop a chrome extension using angular2 and typescript, I have hit a roadblock in trying to access the chrome API (in this case, chrome.bookmarks). I have successfully gained access to the chrome object by following guidance from ...

What is the best way to set up a local node server on a subdirectory?

In my vuejs application, I am looking to replicate a production environment locally where the deployment is on a subfolder such as www.domain.com/subfolder1. Is there a way to configure my local node server so that the application runs on localhost:port/s ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...