Chooce video playback speed
speed:1

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

Share this video with your friends

Send Tweet

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.

This lesson is a Community Resource

A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.

Instructor: 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.

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.

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.

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.

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.

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.

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.