javascript / beginner
Snippet
Verwaltung des Domain-Zustands mit einer JavaScript-Datenklasse
Die Instanziierung von Standard-ES6-Klassen in reaktiven Referenzen kombiniert objektorientierte Kapselung und Getter-Methoden mit dem Reaktivitätssystem von Vue.
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
Erklärung
1
class CartItem {
Deklariert eine objektorientierte Klasse zur Modellierung einzelner Warenkorb-Einträge.
2
constructor(name, price, quantity = 1) {
Initialisiert Objekteigenschaften mit Name, Einzelpreis und einer Standardmenge.
3
get subtotal() { return this.price * this.quantity; }
Definiert einen Getter in der Klasse, der den Gesamtpreis des Artikels bei Bedarf berechnet.
4
const activeItem = ref(new CartItem('Mechanical Keyboard', 120, 1));
Hüllt die Klasseninstanz in eine reaktive Referenz zur nahtlosen UI-Bindung ein.