Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
How to add classes to an element outside of AlpineJS element

I have a simple question but it's driving me mad to work out. I'm using AlpineJS to show and hide content. Normally with alpine, the button and content will be in the same element, but here I have it outside of it. This works. But I cannot add classes to both the button and content div when the content is open or closed.

Can anyone guide me please.

<!-- button -->
<div class="mt-4" x-data="{id: 1}">
    <button 
    @click="$dispatch('open-dropdown',{id})" 
    type="button" 
    class="bg-white hover:bg-gray-50"
    :class="{ 'bg-green-400': open, 'bg-gray-200': !(open) }">
        I'm the button
    </button>
</div>

<!-- popup 1 -->
<div x-data="{ open: false }" 
x-show="open" 
@open-dropdown.window="if ($event.detail.id == 1) open = true" 
@click.away="open = false">
    <div
    class="bg-white hover:bg-gray-50"
    :class="{ 'bg-green-400': open, 'bg-gray-200': !(open) }">
        I'm the content
    </div>
</div>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For this you can move the open state inside the global Alpine.js' $store object that is accessible for all component on the page.

<!-- button -->
<div class="mt-4" x-data="{id: 1}">
  <button @click="$dispatch('open-dropdown',{id})"
          type="button"
          class="bg-white hover:bg-gray-50"
          :class="{ 'bg-green-400': $store.open, 'bg-gray-200': !($store.open) }">
      I'm the button
  </button>
</div>

<!-- popup 1 -->
<div x-data
     x-show="$store.open"
     @open-dropdown.window="if ($event.detail.id == 1) $store.open = true"
     @click.away="$store.open = false">
  <div class="bg-white hover:bg-gray-50"
        :class="{ 'bg-green-400': $store.open, 'bg-gray-200': !($store.open) }">
    I'm the content
  </div>
</div>

<script>
document.addEventListener('alpine:init', () => {
  Alpine.store('open', false)
})
</script>

Since our open state in the store is a simple value, we can just replace every open with $store.open. Note that the popup 1 component still requires an empty x-data attribute.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda