AlpineJS stores
Frontend
brush/src/stores/index
brush/src/components/first-component.ts
brush/src/components/second-component.ts
some-liquid-file.liquid
Creating and using AlpineJS stores requires 2 steps: create a store, and use it in components.
Alpine stores in Brush are persistent. They use the Persist Plugin to save data in localStorage. This is the way to go create a stateful application.
Create a store
Section titled “Create a store”- Edit
brush/src/stores/index.ts. - Declare a store with init data:
export type MessagesStore = { helloWorld: string;};
export function registerAlpineStores() { return { messagesStore: Brush.Persistor.initStore("messagesStore", { helloWorld: "" } as MessagesStore), // Add stores here };}Use in components
Section titled “Use in components”Example to show two-way data binding and reactivity.
A first component
Section titled “A first component”export default function () { Alpine.data("FirstComponent", () => ({}));}A second component
Section titled “A second component”import type { MessagesStore } from "../stores";
export default function () { Alpine.data("SecondComponent", () => ({ initMessage: "Hello World!", messagesStore: {} as MessagesStore,
init() { this.messagesStore = this.$store.messagesStore as MessagesStore; this.reset(); },
reset() { this.messagesStore.helloWorld = this.initMessage; }, }));}Usage in Liquid
Section titled “Usage in Liquid”<div x-data="FirstComponent()"><span x-text="$store.messagesStore.helloWorld"></span></div><div x-data="SecondComponent()"> <input type="text" x-model="$store.messagesStore.helloWorld"> <button type="button" @click="reset">Reset message</button></div>