I'm making a web game with typescript in Vuejs3 but I'm struggling to make my typescript class properties reactive in my .vue components.
I've simplified the class to make it clearer.
Game.ts:
import { Clock } from "@/modules/Clock";
export class Game {
public clock: Clock;
constructor() {
this.clock = new Clock(60);
}
}
Clock.ts:
export class Clock {
private _updateTimeRequest = 0;
public initialTime: number;
public timeLeft: number;
constructor(startTime: number) {
this.initialTime = startTime;
this.timeLeft = startTime;
this.start();
}
private updateTime(): void {
this.timeLeft--;
if (this.timeLeft <= 0) {
this.stop();
}
}
public start() {
this.timeLeft = this.initialTime;
this._updateTimeRequest = setInterval(this.updateTime.bind(this), 1000);
}
public stop() {
clearInterval(this._updateTimeRequest);
}
}
GameView.vue:
import GameClock from "@/components/GameClock.vue";
import { Game } from "@/modules/Game";
import { provide, ref } from "vue";
let game = ref(new Game());
provide("game", game);
</script>
<template>
<div>
<GameClock />
</div>
</template>
<style scoped></style>
GameClock.vue:
<script setup lang="ts">
import { computed, inject } from "vue";
const game = inject("game");
const timeLeft = computed(() => {
return game.value.clock.timeLeft;
});
</script>
<template>
<div>
<span>{{ timeLeft }}</span>
</div>
</template>
<style scoped></style>
So the question is, how do I make my timeLeft property reactive so it can display the countdown of the game.clock instance ?