How to create a custom data- attribute in Apine.js?

26 views Asked by At

I want to create a custom attribute and change the value on click.

I have this:

<div x-data="{ colorred = true }" />

    <div @click="colorred = !colorred" />set red state</div>

</div>

And it works.

But I would also need to have data-state-of-color-red="true" if colorred == true and data-state-of-color-red="false" if colorred == false.

So if it colorred is true it will end up like this:

<div @click="colorred = !colorred" data-state-of-color-red="true" />set red state</div>

otherwise:

<div @click="colorred = !colorred" data-state-of-color-red="false" />set red state</div>

I am not familiar with Alpine how one create data or any attributes on the fly and how also one changes or toggle their change on the fly.

I reckon that one can chain (using the comma) what is done in @click, so perhaps something like:

@click="colorred = !colorred, <and here create/toggle the data- attribute for this element...

?

Thanks in advance for help.

1

There are 1 answers

3
Pippo On BEST ANSWER

You can simply bind your data-attribute to the Alpine variable with the x-bind directive or with its short-hand notation using a simple colon before the attribute name:

<div x-data="{ colorred: true }">

    <div @click="colorred = !colorred"
         :data-state-of-color-red="colorred.toString()"
    >
        set red state
    </div>

</div>

Here I have used toString() to convert the boolean value to a string, otherwise, in case of false, the HTML attribute would be removed.