Categories
Vue 3

How to Add a Menu with Active Item Highlighting with Vue 3?

Spread the love

Sometimes we want to add a menu with the active menu item highlighted in our Vue 3 app.

In this article, we’ll look at how to add a menu with active item highlighting with Vue 3.

Add a Menu with Active Item Highlighting

To add a menu with the active item highlighting in our Vue 3 app, we can listen to the mouseenter and mouseleave events.

We add the highlight to the item that’s hovered over when the mouseenter event is emitted.

And when the mouseleave event is emitted, we clear the highlights on all items.

To do this, we write:

<template>
  <ul>
    <li
      :class="{ hovered: hoveredItem === 'apple' }"
      @mouseenter="hoveredItem = 'apple'"
      @mouseleave="resetHover()"
    >
      apple
    </li>
    <li
      :class="{ hovered: hoveredItem === 'orange' }"
      @mouseenter="hoveredItem = 'orange'"
      @mouseleave="resetHover()"
    >
      orange
    </li>
    <li
      :class="{ hovered: hoveredItem === 'grape' }"
      @mouseenter="hoveredItem = 'grape'"
      @mouseleave="resetHover()"
    >
      grape
    </li>
    <li
      :class="{ hovered: hoveredItem === 'pear' }"
      @mouseenter="hoveredItem = 'pear'"
      @mouseleave="resetHover()"
    >
      pear
    </li>
    <li
      :class="{ hovered: hoveredItem === 'banana' }"
      @mouseenter="hoveredItem = 'banana'"
      @mouseleave="resetHover()"
    >
      banana
    </li>
  </ul>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      hoveredItem: "",
    };
  },
  methods: {
    resetHover() {
      this.hoveredItem = "";
    },
  },
};
</script>

<style scoped>
.hovered {
  color: red;
}
</style>

We have the li elements that have the hovered class applied dynamically.

We apply the class when the hoveredItem ‘s value is the same one that’s set in the mouseenter event handler.

And we call the resetHover method to reset hoveredItem to an empty string when our mouse leaves an item.

We have the hoveredItem reactive property to keep track of which item is highlighted.

And we have the .hovered class that has the color set to red to add the highlighting.

Now when we hover over an item, we should see the item that our mouse hovered over becomes red.

When our mouse leaves the item, then the items turn back to black.

Conclusion

We can add a menu with active items highlighting with Vue 3 easily.

To do this, we just listen to the mouseenter and mouseleave events and applies the class to add the highlight accordingly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *