Dropdown

A menu that opens on click and closes on selection or an outside click. The outside click is a .outside modifier on the root, which Micra removes on destroy.

Markup

<div data-component="dropdown" @click.outside="close">
  <button @click="toggle" data-bind="aria-expanded:open ? 'true' : 'false'" aria-haspopup="menu">
    Options <span>v</span>
  </button>

  <div role="menu" data-show="open">
    <template data-each="items" data-key="id">
      <button role="menuitem" @click="choose" data-bind="data-label:item.label" data-text="item.label"></button>
    </template>
  </div>

  <p>Selected: <span data-text="selected || 'none'"></span></p>
</div>

Component

Micra.define("dropdown", {
  state: {
    open: false,
    selected: "",
    items: [
      { id: 1, label: "Rename" },
      { id: 2, label: "Duplicate" },
      { id: 3, label: "Archive" },
      { id: 4, label: "Delete" },
    ],
  },
  toggle() {
    this.state.open = !this.state.open;
  },
  choose(e) {
    this.state.selected = e.currentTarget.dataset.label;
    this.state.open = false;
  },
  close() {
    this.state.open = false;
  },
});

@click.outside on the root runs close for any click outside the component (Micra 2.9+). The toggle button is inside the root, so the click that opens the menu doesn’t count as outside. Micra removes the listener on destroy.