After an unsuccessful search for a solution, I decided to write a question myself.
My goal is to create a basic drop-down menu component in Vue with a toggle button that collapses the menu when focus leaves the component. Despite using @blur
and @focus
events to maintain focus, I encountered an issue with the toggle button. If I apply the same listeners to it, clicking on the button results in the menu appearing and disappearing instantly, requiring another click to expand it.
You can see the problem demonstrated in this fiddle.
If I remove the listeners from the button, accessing the button after focusing inside the component becomes problematic. It seems like my approach needs adjusting, so here's what I anticipate:
- The toggle button should simply toggle the list's visibility upon clicks
- The list can only be expanded by clicking the toggle button when it's closed
- The list collapses when either clicking the toggle button while it's open or when focus shifts elsewhere, including focusing out of the button itself (i.e., expanding the list by clicking the toggle button and then clicking outside without selecting any items).
EDIT: Thanks to @Sphinx, I successfully achieved the desired dropdown functionality. Here's the updated fiddle.