0 day streak
javascript / beginner
Snippet

Encapsulating Business Logic in Domain Classes

Object-oriented programming (OOP) principles like encapsulation allow bundling data and domain calculations within standard JavaScript classes, which can then be wrapped in Vue's reactivity system.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { ref } from 'vue';
class CartItem {
constructor(name, price, quantity = 1) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
getTotalPrice() {
return this.price * this.quantity;
}
}
const item = ref(new CartItem('Notebook', 12, 3));
vue
Breakdown
1
class CartItem {
Defines an OOP class to represent shopping cart items and their business logic.
2
constructor(name, price, quantity = 1) {
Initializes object properties when a new instance is created with the new keyword.
3
getTotalPrice() { return this.price * this.quantity; }
A class method calculating total cost using encapsulated instance properties.
4
const item = ref(new CartItem('Notebook', 12, 3));
Instantiates the CartItem class and wraps it in a reactive ref for Vue reactivity.