javascript / intermediate
Snippet
Encapsulating Domain Models with ES6 Classes and Vue Reactivity
ES6 classes allow you to encapsulate business logic and private fields within domain models. Wrapping class instances in Vue's reactive() keeps internal state synchronized with Vue's reactivity system while retaining object-oriented encapsulation and method behaviors.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { reactive } from 'vue';class UserAccount {#balance = 0;constructor(name, initialBalance = 0) {this.name = name;this.#balance = initialBalance;}get balance() {return this.#balance;}deposit(amount) {if (amount <= 0) throw new Error('Amount must be positive');this.#balance += amount;}}export function useAccount(name, initialDeposit) {const account = reactive(new UserAccount(name, initialDeposit));return { account };}
vue
Breakdown
1
class UserAccount {
Defines an ES6 class to structure account state and operations.
2
#balance = 0;
Declares a private class field to prevent unauthorized direct mutations.
3
deposit(amount) {
Encapsulates business mutation logic and input validation.
4
const account = reactive(new UserAccount(name, initialDeposit));
Instantiates the class and makes it reactive within Vue's Composition API.