[Vuejs]-Change image icon when the active tab is change

0πŸ‘

  1. Use some default value for your v-model, 'tab' to make a tab active by default. (I am using the name property of the tab in v-model but you can use any unique property you want.)
  2. Use this v-model to check which tab is active and using the condition operator, update the icon. (I used dummy icons you can use yours.)

Here’s the demo where you should see that when the tab is active, the colorful flight icon would show otherwise black flight icon would be displayed.

<!DOCTYPE html>
<html>
  <head>
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
  </head>
  <body>
    <div id="app">
      <v-app>
        <v-main>
          <v-container>
            <v-tabs
              v-model="tab"
              >
              <v-tab
                v-for="(item, index) in items"
                :key="index"
                :href="`#${item.name}`"
                class="home-tabs"
                active-class="activeTab"
                >
                <img :src="tab == item.name ? item.icon : inactive_icon" />
                {{ item.name }}
              </v-tab>
            </v-tabs>
          </v-container>
        </v-main>
      </v-app>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
    <script>
      new Vue({
        el: '#app',
        data () {
      return {
        tab: 'Flights',
        inactive_icon: 'https://www.svgrepo.com/show/413929/fly.svg',
        items: [
          { icon: "https://www.svgrepo.com/show/424654/airplane-flight-travel.svg", name: "Flights" },
          { icon: "https://www.svgrepo.com/show/424654/airplane-flight-travel.svg", name: "Hotels" },
          { icon: "https://www.svgrepo.com/show/424654/airplane-flight-travel.svg", name: "Flights + Hotels" },
          { icon: "https://www.svgrepo.com/show/424654/airplane-flight-travel.svg", name: "Students" },
        ],
      }
      },
        vuetify: new Vuetify(),
      })
    </script>
  </body>
</html>
</html>

Leave a comment