Home  >  Q&A  >  body text

How to dynamically add activity class for menu loop in Vue Js?

<p>How to add an active class in a loop that dynamically displays menus? I can't set activity class for opened menu. </p> <pre class="brush:php;toolbar:false;"><a v-bind:href="module.route" class="nav-link"> //module.route is a database column <i :class="module.icon" ></i> //module.icon is a database column <p> {{ module.name }} //module.name is a database column </p> </a></pre> </li> <p>It displays the menu list from the database. Now I just want to make the open menu active. </p>
P粉793532469P粉793532469421 days ago365

reply all(1)I'll reply

  • P粉600845163

    P粉6008451632023-08-26 13:08:54

    I did this.

    <!-- App.vue HTML 部分 -->
    <li v-for = "(tab, index) in tabs" :key="index" class="nav-link" @click="active_tab = tab" v-bind:class="{ 'active' : tab === active_tab }">
        ...
    </li>
    

    I added all the tabs I wanted in an array called tabs.

    <script>
    
    export default {
      name: 'Home',
    
      data() {
        return {
          active_tab: "Tab1",
          tabs: ["Tab1", "Tab2", "Tab3"]
        }
    }
    
    </script>
    

    This will create a <li> element for each tab in the array tabs.

    All elements will have the nav-link class, and use v-bind, if the variable active_tab is equal to tab, will add active to the element's class list. Whenever the user clicks one of the tabs, use @click to change the active_tab to the tab that the user clicked.

    style

    .nav-link {
        background-color: var(--primary-color);
        /* 正常时元素的外观 */
    }
    .nav-link.active {
        background-color: var(--hover-color);
        /* 当元素处于活动状态时 */
    } 
    

    reply
    0
  • Cancelreply