Skip to content

Instantly share code, notes, and snippets.

@chrissearle
Last active June 30, 2023 08:44
Show Gist options
  • Save chrissearle/6324fadc2a48e4c81829c605e22544ff to your computer and use it in GitHub Desktop.
Save chrissearle/6324fadc2a48e4c81829c605e22544ff to your computer and use it in GitHub Desktop.
DaisyUI close menu on vue route change
DaisyUI navbar - dropdown autoclose on vue route change
DaisyUI navbar dropdown toggles the display of a menu by adding/removing the attribute "open" to
the <details> tag in the submenu.
Changing route in vue (via e.g RouterLink) does not update the navbar which is outside the
router-view so the menu stays open.
So - this code watches for a route change - and removes open. It finds the elements by using template refs.
The ref on the element must have the same value as the name of the ref variable in the script.
<script setup lang="ts">
import { useRoute } from 'vue-router'
import { watch, ref } from 'vue'
const route = useRoute()
const submenu1 = ref<HTMLElement | null>(null)
const closeMenu = (element: HTMLElement | null) => {
if (element && element.hasAttribute('open')) {
element.removeAttribute('open')
}
}
const closeMenus = () => {
closeMenu(submenu1.value)
}
watch(route, () => {
closeMenus()
})
</script>
<template>
<div class="navbar bg-base-100">
<div class="flex-1">
<a class="btn btn-ghost normal-case text-xl">daisyUI</a>
</div>
<div class="flex-none">
<ul class="menu menu-horizontal px-1">
<li><a>Link</a></li>
<li>
<details ref="submenu1">
<summary>
Parent
</summary>
<ul class="p-2 bg-base-100">
<li><a>Some link that changes route (e.g. RouterLink)</a></li>
<li><a>Some link that changes route (e.g. RouterLink)</a></li>
</ul>
</details>
</li>
</ul>
</div>
</div>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment