javascript / intermediate
Snippet
Encapsulating Business Logic with Class Models in Shallow Reactive State
Deep reactivity proxies in Vue can disrupt class instances that rely on private fields (`#field`) or strict prototype inheritance. By utilizing `shallowReactive`, developers can safely integrate object-oriented domain models with encapsulated private state while still tracking top-level object mutations in the UI.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { shallowReactive } from 'vue';class BankAccount {#balance = 0;constructor(initialBalance) {this.#balance = initialBalance;}deposit(amount) {if (amount <= 0) throw new RangeError('Deposit must be positive');this.#balance += amount;}get balance() {return this.#balance;}}const accountState = shallowReactive(new BankAccount(100));
vue
Breakdown
1
class BankAccount {
Defines an object-oriented domain model implementing business invariants and encapsulation.
2
#balance = 0;
Declares a truly private ECMAScript class field inaccessible from outside the class scope.
3
const accountState = shallowReactive(new BankAccount(100));
Wraps the class instance in a shallow reactive proxy to avoid breaking private field accessors.