Programmatic Menus in vuejs

larbi jirari
Vue.js Developers
Published in
2 min readMay 30, 2019

--

You have an web app created using vuejs and you have a menu in it ? this article is definitely for you.

In this article you will see how routes will appear in your menu without having to add anything in your Menu component.

While developing an application using Vuejs i was asked to add pages in a menu, but while doing that i found that it can be done grammatically.

here is a working CodeSandbox and a Github repo.

Let’s say that we have a menu structured this way

i suppose that you have an operating app and routes is already enabled.

here’s the initial router.js file

let’s add our first route

i added an attribute called meta in the line 18, this attribute is used to enrich route, you can add whatever you want there, in most cases it’s used to add a label or show/hide route in the menu.

i’ll do the same thing for the other routes.

the complete file will look like the following

let’s create folder called Menu under our components folder

lets start by the Menu/index.vue

the this.$router.options.routes will return the content of router file.

then Menu/MenuItem.vue

we will do a recursive call to the same component if the route has a child component, i was inspired by the work of Alex Jover Morales from alligator.io

to get the active route i used exact-active-class=”active”, this adds a class .active to the active menu item.

and there you go!

here is a working CodeSandbox and a Github repo.

if you have any questions let me know, i’ll be glad to help.

--

--