This package provides typescript support for Alpine.js, and is inspired by archtechx/alpine-typescript and kaorun343/vue-property-decorator.
npm install @rubenbimmel/alpine-class-component
Write a component:
import { AlpineComponent, Component } from '@rubenbimmel/alpine-class-component';
@Component
export default class Dropdown extends AlpineComponent {
show = false;
open() {
this.show = true
}
close() {
this.show = false
}
}
Register a component:
import { Alpine } from '@rubenbimmel/alpine-class-component';
import Dropdown from './components/dropdown/dropdown';
Alpine.data('dropdown', Dropdown);
Alpine.start();
Use it in a template:
<div x-data="dropdown">
<button @click="open()">Expand</button>
<span x-show="show" x-on:click.away="close()" x-cloak>
Content...
</span>
</div>
You can pass in additional parameters to the initial data object using a constructor:
import { AlpineComponent, Component } from '@rubenbimmel/alpine-class-component';
@Component
export default class Person extends AlpineComponent {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
get name() {
return `${this.firstName} ${this.lastName}`;
}
}
<div x-data="person('John', 'Doe')">
<span x-text="name"></span>
</div>
Init functions are automatically execute before the component is rendered:
import { AlpineComponent, Component } from '@rubenbimmel/alpine-class-component';
@Component
export default class Example extends AlpineComponent {
init() {
console.log('init');
}
}
Getters can be used as normal:
import { AlpineComponent, Component } from '@rubenbimmel/alpine-class-component';
@Component
export default class Person extends AlpineComponent {
firstName = 'John';
lastName = 'Doe';
get name() {
return this.firstName + ' ' + this.lastName;
}
}
Use the Ref decorator to declare refs:
<div x-data="example">
<button @click="remove()">Remove Text</button>
<span x-ref="text">Hello 👋</span>
</div>
import { AlpineComponent, Component, Ref } from '@rubenbimmel/alpine-class-component';
@Component
export default class Example extends AlpineComponent {
@Ref() text: HTMLSpanElement;
remove() {
this.text.remove();
}
}
Use the Watch decorator to register watchers:
import { AlpineComponent, Component, Watch } from '@rubenbimmel/alpine-class-component';
@Component
export default class Dropdown extends AlpineComponent {
show = false;
@Watch('show')
onShowChange(value: boolean, oldValue: boolean) {
console.log(value, oldValue);
}
}