When setting up, I create something like the following:
const abc = reactive(new AnotherClass())
return {abc}
As I continue working on the component, I am able to call a method of this class using abc.Func(), or access some field. Everything appears to be functioning properly. However, let's consider a scenario: in the class constructor, we create an event listener that listens for a specific event and then sets either true or false for one of the class fields. This is where an issue arises - when trying to display this field in the component that should be changed by the handler, it becomes apparent that the class fields are not reactive. Even though the handler clearly changes the value of the field, this change is not reflected in the component. Fields only become reactive when you also use the reactive keyword for fields within the class. But why is this necessary? I already made the entire class reactive in the setup phase. Why do I also need to specify ref and reactive inside the class?
Code snippet from the component:
<template>
<div style="width: 200px; height: 200px">{{player.audioPlayer.isPlaying}}</div>
</template>
setup(props) {
const player = reactive(new AnotherClass())
return {player}
},
Class definition:
private _onPlaying = this.onPlaying.bind(this)
constructor() {
this.audioPlayer = {
active: false,
initialized: false,
element: new Audio(''),
isPlaying: false,
currentPlaying: {
playlist: [],
index: 0
}
}
this.audioPlayer = reactive(this.audioPlayer) // if comment this out, no changes will be visible in the component after setting onPlaying to true
this.init()
}
private init(){
this.audioPlayer.element.addEventListener('playing', this._onPlaying)
this.audioPlayer.initialized = true
}
private onPlaying() {
this.audioPlayer.isPlaying = true
}