javascript / beginner
Snippet
Managing Domain State with a JavaScript Data Class
Instantiating standard ES6 classes inside reactive references combines object-oriented encapsulation and helper getters with Vue's reactivity system.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { ref } from 'vue';class CartItem {constructor(name, price, quantity = 1) {this.name = name;this.price = price;this.quantity = quantity;}get subtotal() {return this.price * this.quantity;}increment() {this.quantity += 1;}}const activeItem = ref(new CartItem('Mechanical Keyboard', 120, 1));
vue
Breakdown
1
class CartItem {
Declares an object-oriented class to model individual shopping cart entities.
2
constructor(name, price, quantity = 1) {
Initializes object properties with name, unit price, and a default quantity.
3
get subtotal() { return this.price * this.quantity; }
Defines a class getter calculating the line item total on demand.
4
const activeItem = ref(new CartItem('Mechanical Keyboard', 120, 1));
Wraps the class instance in a reactive reference for seamless UI binding.