Files
esengine/extensions/cocos/cocos-ecs/assets/scripts/mvvm/UserInfoViewModel.ts

128 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-07-08 08:55:55 +08:00
import { ViewModel, observable, computed, command, viewModel } from '@esengine/mvvm-ui-framework';
/**
*
* 使 MVVM
*/
@viewModel
export class UserInfoViewModel extends ViewModel {
public get name(): string {
return 'UserInfoViewModel';
}
/**
* - 使 @observable
*/
@observable
userName: string = '未知用户';
/**
*
*/
level: number = 1;
/**
*
*/
@observable
score: number = 0;
/**
*
*/
@observable
coins: number = 100;
/**
* 线
*/
@observable
isOnline: boolean = false;
/**
*
*/
@computed(['userName', 'level'])
get displayName(): string {
return `${this.userName} (Lv.${this.level})`;
}
/**
* 线
*/
@computed(['isOnline'])
get onlineStatusText(): string {
return this.isOnline ? '在线' : '离线';
}
/**
* +
*/
@computed(['score', 'coins'])
get totalAssets(): number {
return this.score + this.coins;
}
/**
* - 使 @command executeCommand('addScore')
*/
@command()
public addScore(amount: number = 10): void {
this.score += amount;
}
/**
* - canExecute
*/
@command('canAddCoins')
public addCoins(amount: number = 5): void {
this.coins += amount;
}
/**
* 1
*/
public canAddCoins(): boolean {
return this.level > 1;
}
/**
* - canExecute
*/
@command('canLevelUp')
public levelUp(): void {
this.level += 1;
this.score += this.level * 100; // 升级奖励
}
/**
*
*/
public canLevelUp(): boolean {
return this.score >= this.level * 100;
}
/**
* 线
*/
@command()
public toggleOnlineStatus(): void {
this.isOnline = !this.isOnline;
}
/**
*
*/
public resetUserData(): void {
this.batchUpdate({
userName: '新用户',
level: 1,
score: 0,
coins: 100,
isOnline: false
});
}
}