Counter component
A simple reactive counter that increments and decrements a displayed number. This is the simplest possible js-toolkit component, making it a great starting point.
What we're building
A counter with two buttons (+ and −) and a number display. Clicking the buttons updates the count in real time. This demonstrates refs for DOM access and event handling via the on<Ref><Event> naming convention.
HTML markup
The HTML uses data-component to mark the root element and data-ref to expose three child elements to the component:
<div data-component="Counter">
<button data-ref="remove">-</button>
<div data-ref="counter">0</div>
<button data-ref="add">+</button>
</div>JavaScript component
The component declares its refs in static config. A getter/setter pair on count reads from and writes to the counter ref. Click handlers are auto-bound by naming them on<Ref>Click:
import { Base } from '@studiometa/js-toolkit';
export default class Counter extends Base {
static config = {
name: 'Counter',
refs: ['add', 'remove', 'counter'],
};
get count() {
return Number(this.$refs.counter.innerHTML);
}
set count(value) {
this.$refs.counter.innerHTML = value;
}
onAddClick() {
this.count += 1;
}
onRemoveClick() {
this.count -= 1;
}
}App setup
Register the component so js-toolkit auto-mounts it on any matching data-component="Counter" element:
import { registerComponent } from '@studiometa/js-toolkit';
import Counter from './Counter.js';
registerComponent(Counter);Live demo
Further reading
- Refs guide — learn how
data-refconnects HTML to your component - Events guide — the
on<Ref><Event>naming convention - Base class API — full reference for the
Baseclass