I have a simple scoring app that uses Vue 3 to maintain the scores and totals. I have a global teams object that contains all the scores. My Vue 3 app updates my scores quite happily within itself, but I also need to access the teams object outside of the Vue app to do other non-user interface activities, like saving etc. and i'd like to keep them sync'd.
My global teams object looks like this:
let teams = [];
teams[0] = {
players: [
{ name: "Player 1" },
{ name: "Player 2" }
],
scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
};
teams[1] = {
players: [
{ name: "Player 1" },
{ name: "Player 2" }
],
scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
};
I link it to my Vue 3 app like this:
data() {
return {
home: teams[0],
away: teams[1]
};
},
If I update a score on the home or away object within Vue, the global teams object is not updated. For example I have a Save function (outside of Vue) that relies on the teams object be kept in sync with updates to home and away.
Is there a way to do this? Am I going about it all wrong? I could move my Save function into Vue but I was trying to separate out my user interface logic. I do have other functions that need access to a sync'd teams object and i'd rather not add everything into the Vue app.
Thanks in advance. J.
You could maybe use computed getters and setters instead of data:
computed: {
home: {
get() { return teams[0] },
set(val) { teams[0] = val }
},
away: {
get() { return teams[1] },
set(val) { teams[1] = val }
},
}
I do appear to have found an ugly solution. I just copy the home and away objects back to the teams object during a Vue 3 update, like this:
updated() {
teams[0] = this.home;
teams[1] = this.away;
}
Although it works, it does seem a bit clunky, as it copies the whole object back rather than just the bit that changed.