Burger Sasha
Burger Sasha

Reputation: 175

How to add conditional classes with alpine JS?

How to access the value of a variable from another component and use for condition classes?

header.liquid

<button 
            type="button"
            title="Cart button"
            @click="$dispatch('toggle-cart')"
            class="rounded-full py-1 px-2 text-[12px]"
            :class="{[showCartDrawer]: true, 'bg-white text-black': bg-black text-white }"
          >
              <span class="">{{ 'templates.cart.cart' | t }}</span>
              <span x-text="cart_count" class="cart__count"> {{ cart.item_count }} </span>
          </button>

cart-drawer.liquid

    <div x-data="{ 
        showCartDrawer: false,
        }
     }"
    x-show="showCartDrawer"
    @cart-updated.window="updateCart;"
    @toggle-cart.window="showCartDrawer = !showCartDrawer">
    </div>

Upvotes: 0

Views: 1256

Answers (1)

Dauros
Dauros

Reputation: 10502

You can use the global Alpine.store() object for sharing a state variable between components. Here I created a store object cartDrawer with the show property and a method to toggle its value. You can access this state variable like $store.cartDrawer.show:

<div x-data="">
  <button type="button" title="Cart button"
          @click="$store.cartDrawer.toggle()" 
          class="rounded-full py-1 px-2 text-[12px]"
         :class="$store.cartDrawer.show ? 'bg-white text-black' : 'bg-black text-white'">
    <span class="">{{ 'templates.cart.cart' | t }}</span>
    <span x-text="cart_count" class="cart__count"> {{ cart.item_count }} </span>
  </button>
</div>

<div x-data="" x-show="$store.cartDrawer.show"></div>

<script>
document.addEventListener('alpine:init', () => {
  Alpine.store('cartDrawer', {
    show: false,

    toggle() {
      this.show = !this.show
    }
  })
})
</script>

Upvotes: 1

Related Questions