Burger Sasha
Burger Sasha

Reputation: 175

How to open modals using global string store in alpine

Using alpine I am trying to replicate the thinking of global state like in react to open various menu modals if the global state is equal to the current string value. eg 'menu', 'search'. This is so if one modal is open and the user opens another, the others close

Firstly I am defining the state

document.addEventListener('alpine:init', () => {
  Alpine.store('panel', {
    type: "",
    toggle(string) {
      this.type = string
    }
  })
})

Button

<button
   @click="$store.panel.toggle('menu')"
   :class="$store.panel.type === 'menu' ? 'panel-open' : ''"
>
</button>

So far this is working correctly and has been tested with console logs. The code for the model is where I am having trouble, it does not work but I feel it's close

<div
  x-data="{ showMenu: false }"
  x-show="showMenu"
  @toggle-menu.window="showMenu = $store.panel.type === 'menu'"
>
  <div
    x-show="showMenu"
    x-transition:enter="transition-height ease-in-out duration-1000"
    x-transition:enter-start="h-0"
    x-transition:enter-end="h-screen"
    x-transition:leave="transition-height ease-in-out duration-1000"
    x-transition:leave-start="h-screen"
    x-transition:leave-end="h-0"
  >
    // stuff
  </div>
</div>

Upvotes: 0

Views: 396

Answers (1)

harceo
harceo

Reputation: 133

You could change your x-show to check the value of menu. Working CodeSandbox

// Buttons that set a name
<div x-data>
    <button @click="$store.panel.toggle('main_menu')">
        Open Main Menu
    </button>
    <button @click="$store.panel.toggle('search_menu')">
        Open Search Menu
    </button>
</div>
// Menu if names match
 <div x-data>
      <div x-show="$store.panel.openMenu == 'main_menu'"">
        // Main
      </div>
      <div x-show="$store.panel.openMenu == 'search_menu'">
        // Search
      </div>   
    </div>
<script>
      document.addEventListener("alpine:init", () => {
        Alpine.store("panel", {         
          openMenu: "",
          toggle(string) {
            if(this.openMenu == string){
              this.openMenu = ""
            }  else{
              this.openMenu = string;                     
            }
          }
        });
      });
    </script>

Upvotes: 1

Related Questions