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