DEV Community

Cover image for Search submenu tabs with flatMap and Vuetify
Bruno Panassi
Bruno Panassi

Posted on

Search submenu tabs with flatMap and Vuetify

On these days on work i had to add a search in a menu that has v-tabs on it, and when i finished, there was two approaches on how to do this. Of course that the changes in the system was more complex than in this example, but i hope that this can help someone.

Before we dive into

The first approach was more simple (at least for me), that uses only map and filter.The second approach was made by a work colleague that uses a v-autocomplete and flatMap(that i had never heard before).

Structure

So we have here a menu that have a sub menu, so you can imagine him like this:
menu-structure

Yes, a computed property that is an Array of a Object that has two props:

  • name: Title of the menu (String)

  • sub: Content of the sub-menu (Array of strings)

And this will be the data for the v-tabs that have a v-menu on each tab. I will focus here only in the JS code, but you can check the HTML in this link of CodePen

1º Approach

So the first approach will be a map on the computed tabs itself, that returns only the sub names that includes the letters of the variable search(used by a v-text-field), and then returns only the tabs that have the subs:
first-approach
The reason i thought this is the simplest way its for the familiar methods (filter and map) but this approach its not the clever or cleaner one.

2º Approach

This approach uses the flatMap, that maps a nested array to a single array (simplifying the explanation), wich in this case it's the better option because we need only the values of the sub property. And then filter only the values that matchs with the search variable.
second_approach
In this example this computed property it's been used in a v-auto-complete component.

Conclusion

So for me the 2º approach was the cleaner one, both for code and screen design, and you can combine the search of the menu with a $emit method to show the screen of the selected menu.

Thanks for reading, i hope that this was useful for you!

Discussion (0)