pass data using alpine js @click

43 Views Asked by At

I have a link with alpinejs @click event

<a class="parent post_no" data-value="<?php echo $total_posts_parent ?>" @click="filterPosts(<?= $category->term_id; ?>)"><?= esc_html( $category->name); echo " ". "(" .$total_posts_parent . ")" ?></a>

how can I add the Var $total_posts_parent to the @click and have it received in my alpine function?

Function

Want the on @click $total_posts_parent to populate total

Alpine.data("filterPosts", (adminURL) => ({
posts: "",
limit: 6,
category: 0,
post_type_js: post_id,
showDefault: true,
showFiltered: false,
offset: 0,
total: 0, // want to get the value from the varible here
1

There are 1 best solutions below

4
Pippo On BEST ANSWER

With $el.dataset.value you can access to the data-value value of the current element, you can use it in the @click event or directly in the filterPosts() method:

@click="total += parseInt($el.dataset.value) || 0; filterPosts(<?= $category->term_id; ?>)">

or:

@click="filterPosts($el.dataset.value, <?= $category->term_id; ?>)">

.....

<script>

Alpine.data("filterPosts", (adminURL) => ({

   ......

   filterPosts: function (theValue, termId) {

       this.total += parseInt(theValue) || 0;
       
       .....
   }

</script>

or:

Alpine.data("filterPosts", (adminURL) => ({

   ......
    
    total: 0,

    filterPosts: function ($someData) {

        this.total += parseInt(this.$el.dataset.value) || 0;

    }