Update a count state value with the x-on event listener directive in Alpine JS

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

In this lesson, we define a "count" state value with the x-data directive provided by Alpine JS. This defines a new scoped component, which can have access to this state.

We then display the "count" value in our HTML with the x-text directive, which updates an element's innerText value.

We also hook up buttons with click event listeners with x-on:click, which allows us to modify the count value as desired.

Instructor: [0:00] We have two buttons here and a bit of text that says the current count is . The buttons say -1 and +1 and we want to update the count value when they are clicked.

[0:11] Let's add an x-data attributes to our wrapping <div> and define an object which will have a count state value set to . We have just defined a component and that count state value will be available within the scope of this component.

[0:25] To output the value of this count, we can use another Alpine JS directive, x-text, which will update the inner text value of an element. The here is now our actual state value. Let's verify this by changing the value to 2 in our data object. You can see the value updated in the DOM element.

[0:44] For both buttons, I will add another directive, x-on, used to define event listeners. Here we're listening to the click event, so we'll use x-on:click. There is a shorthand syntax available for event listeners, you can use the @ symbol instead of x-on.

[1:02] For the first button, I want to set the count value to count-1, count--. For the other one, we'll set it to count++. Let's try it out. Yep, it works.

[1:16] Let's say below a paragraph, we want to have a reset button that sets the counts to . If I create another button down here and set the @click to be count = , well, it doesn't work. This is because the count value is only available within the scope of the components where it's defined. If we move the button up inside the wrapper, increment the count a bit and click resets. It now works.

[1:41] As a recap, we define the state object with the x-data directive which makes the state available within the component scope. We then use the x-text to display the count value and listen to click events with x-on or @click where we can update the state according to our needs.