Search code examples
typescriptvue.jsglobal-variablesvuejs3

How to manage global variables and functions in vue3, typescript


I've just entered the vue and everything is confusing. I'm here for advice.

There is data that should be used for global and also I want to provide various functions that process this data. At first, it was approached with a global variable declaration. But because of functions, I created a class that combines data and functions, and declared them as static. Data was initialized in the class's constructor.(with Axios get) In addition, the object was declared in setup() of App.vue to use like a singletone.

<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
    }
  }

Is this the best way? or is there any better way for global variables and functions? If singleton is a right way, I think that without static just sharing the singleton object by provide/Inject is better... right? Please give me some advice.

UPDATE using composible

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,
  }
}


Solution

  • I think that's a perfect candidate for composable

    Here is a basic example:

    <script setup>
    // DataName.vue
    import { UseDataManager } from './DataManager'
    
    const dataManager = UseDataManager()
    </script>
    
    <template>{{ dataManager.getDataName() }}</template>
    
    // DataManager.ts
    
    const dataManager = new DataManager();
    export function UseDataManager(){
      return dataManager;
    }