[Vuejs]-Dynamic navigation component in Vue.js

0πŸ‘

βœ…

I finally solved it using another approach I think is more correct.

Navbar.vue

<template>
  <div class="navbar">
    <nav>
      <ul>
        <li v-bind:class="{ active: isActive('login') }">
          <a href="/login">Log in</a>
        </li>
        <li v-bind:class="{ active: isActive('signup') }">
          <a href="/signup">Sign up</a>
        </li>
      </ul>
    </nav>
  </div>
</template>

<script>
  export default {
    name: 'navbar',
    data () {
      return {
        path: window.location.pathname
      }
    },
    methods: {
      isActive (page) {
        return this.currentPage === page
      }
    },
    computed: {
      currentPage () {
        if (this.path.length === 1) return ''
        const endIndex = this.path.indexOf('/', 1)
        return (endIndex === -1)
          ? this.path.substring(1)
          : this.path.substring(1, endIndex)
      }
    }
  }
</script>
πŸ‘€user1183772

0πŸ‘

You don’t use the single file component format correctly. You create a component instance and export that, where you should only export the options object used to create a component ( the object that you pass to new Vue({... This object })

πŸ‘€Linus Borg

0πŸ‘

You can make use of the route’s path property, check out the doc here…

<template>
 <div class="sidebar sidebar-main sidebar-fixed">
   <div class="sidebar-content">
      <div class="sidebar-category sidebar-category-visible">
       <div class="category-content no-padding">
        <ul class="navigation navigation-main navigation-accordion">
         <li :class="{ active: isActive('dashboard') }">
          <router-link to="/dashboard">Dashboard</router-link>
         </li>    

         <li :class="{ active: isActive('profile') }">
          <router-link to="/dashboard">Profile</router-link>
         </li>    
        </ul>
       </div>
      </div>
     </div>
    </div>
</template>

<script>
 export default {
  name: 'SideBar',      
  methods: {
   isActive(page) {
     return this.$route.path.indexOf(page) !== -1;
   }
  }
 }
</script>

Leave a comment