how to use alpine.js in javascript

To use Alpine.js in JavaScript, first include the alpine.js script in your HTML file:

<script src="https://cdn.jsdelivr.net/npm/alpinejs@2.7.3/dist/alpine.js"></script>
83 chars
2 lines

Then, you can start using Alpine.js in your JavaScript like this:

index.tsx
// Define a new Alpine.js component
const app = () => {
  return {
    message: 'Hello, world!',
    toggle() {
      this.message = (this.message === 'Hello, world!') ? 'Goodbye, world!' : 'Hello, world!';
    }
  }
}

// Mount the component on a specific element in your HTML
document.addEventListener('DOMContentLoaded', () => {
  Alpine.mount('#app', app());
});
367 chars
15 lines

In this example, we define a new Alpine.js component called app that has a message property and a toggle method. Then, we mount the component on a specific element in our HTML by calling Alpine.mount('#app', app()).

Now, if we have an element in our HTML with an id of app and a reference to x-data="app()", we can use the component like this:

<div id="app" x-data="app()">
  <h1 x-text="message"></h1>
  <button x-on:click="toggle()">Toggle message</button>
</div>
122 chars
5 lines

This will render a heading that displays the current value of the message property, and a button that toggles the value when clicked.

Alpine.js is a powerful tool for creating declarative UIs in JavaScript, and it can dramatically simplify your front-end development workflow.

gistlibby LogSnag