'Vue3 reactive and encapsulation
I am new to Vue and I am currently using Vue3. As a learning exercise, I am making a simple login plugin and it is going well. I am using reactive() with an instance of the class below, but I am having a little bit of trouble with getting property changes to update if they are assigned internally. Here is the code in question:
class dtAuthHandler {
private _IsLoggedIn: boolean = false;
public get IsLoggedIn(): boolean {
return this._IsLoggedIn;
}
public set IsLoggedIn(value:boolean)
{
this._IsLoggedIn = value;
}
Login = () => {
// More stuff here, internal state, etc.
this.IsLoggedIn = true;
}
Logout = () => {
// More stuff here, internal state, etc.
this.IsLoggedIn = false;
}
}
Here is a simple function that I am using to demonstrate the toggling of the login status. In the first case, I can set the property directly and the UI updates as expected, so great. In the second case, I would like to use specific Login()/Logout() functions so that the class can maintain some kind of internal state, talk to servers, etc. The problem is that I can't figure out how to get the UI to update when the 'IsLoggedIn' property is set internally.
toggleLogin: function () {
// First Case:
// Works great, makes sense to me.
//this.$dtAuth.IsLoggedIn = !this.$dtAuth.IsLoggedIn;
// Second Case:
// This updates the state of the class just fine, but the UI doesn't get updated.
// What to do?
if (!this.$dtAuth.IsLoggedIn) {
this.$dtAuth.Login();
} else {
this.$dtAuth.Logout();
}
// This seems like a hack....
//this.$forceUpdate();
}
My best guess is that 'reactive()' expects the properties to be set externally, and simply isn't aware when they are set internally, that or I am missing something obvious. What is the best way to handle these types of situations?
For those that are interested, this is how the plugin is setup:
export default class dtAuth {
private authState = new dtAuthHandler();
install = (app: App) => {
app.config.globalProperties.$dtAuth = reactive(this.authState);
}
}
However, it should be known that I get the same behaviour if the reactive instance is a member of data in a class component, e.g.
data() : return { auth: reactive(authState) };
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
