Dynamic SideNav in Vue.js

Tanner Comes
Nov 6 · 2 min read

I was faced with a problem when building League of Tips: I was logged in, but I still saw the Login and Signup navigation items. It looked like this:

I grew attached to using the Alien icon for “Signup”… Might keep it that way.

Initially, I was importing a navigation.json file to my SideNav.vue component and iterating it in a v-for loop. I did this in the spirit of keeping the view file small, but dynamic navigation couldn’t work like that. Here’s what it looked like:

/* Snippet from navigation.json */[  {    "nav": "/",    "title": "Home",    "icon": "mdi-home"  },  {    "nav": "/Champion",    "title": "Champion Tips",    "icon": "mdi-lightbulb-outline"},...]/* And in my view file... */
<script>import nav from '../api/navigation.json';export default {
data() {
return {nav}
}
</script>

Since my conditions are based on my Vuex store, I would need to import the store to navigation.json and really I just prefer not to do that. So I nixed the .json file and dumped its contents into the data object:

data() {
return nav: [...]
}

And to each navigation object, I added a condtition value as a function, to say whether it should show:

{  nav: '/',  title: 'Home',  icon: 'mdi-home',  condition: () => true}

This navigation item should always show, so I just kick back true. But for ones that depend on something, I return that value:

{  nav: '/Login',  title: 'Login',  icon: 'mdi-login',  condition: () => {    return !this.$store.state.userModule.user  }}

And in my markup, I just add a v-show attribute (If you haven’t noticed yet, by the way: I’m using Vuetify):

<v-list-item 
:to=”n.nav”
v-for=”n in nav”
v-show=”n.condition()”
key=”n.nav”>
...
</v-list-item>

Easy peasy, nice and breezy.

Tanner Comes

Written by

https://tanner.com.es. Developer of the working-titled League of Tips, a League of Legends champion interaction resource

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade