效果预览

vue3【实战】菜单导航(高亮当前路由,鼠标悬浮下标、页面滚动顶部悬浮并变色)_vue3

完整代码

<template>
  <!-- 导航 -->
  <nav class="fixed flex items-center p-2 w-full nav-bg1" :class="{ 'nav-bg2': y }">
    <img src="/EC_Logo.jpg" class="w-12 h-12 lt-sm:mx-auto logo" alt="logo" />
    <router-link
      class="routerLink"
      :class="{ activeLink: route.path === item.to }"
      :to="item.to"
      v-for="item in linkList"
      :key="item.to"
      linkList
      >{{ item.name }}</router-link
    >
  </nav>
  <!-- 因 fixed 定位,需要添加一个空 div 撑开高度 -->
  <div class="h-16"></div>

  <!-- 为了演示页面滚动添加的空div -->
  <div class="h-[4000px]"></div>
</template>

<script setup lang="ts">
let linkList = [
  {
    to: '/',
    name: '首页'
  },
  {
    to: '/community',
    name: '社区'
  },
  {
    to: '/study',
    name: '学习'
  },
  {
    to: '/about',
    name: '关于'
  }
]

// 获取滚动条y轴坐标
const { y } = useWindowScroll({ behavior: 'smooth' })

// 获取当前路由
let route = useRoute()
</script>

<style scoped lang="scss">
.routerLink {
  @apply relative color-white text-xl px-8 py-2 font-300 cursor-pointer;
  &:hover {
    @apply font-600;
    &::after {
      content: '';
      @apply absolute bg-gray-100 w-8 h-[1px] bottom-[0.2rem] left-[calc(50%-1rem)];
    }
  }
}
a {
  text-decoration: none;
}
.logo {
  border-radius: 50%;
}

.nav-bg1 {
  background-color: #092c78;
}

.nav-bg2 {
  background-color: #f9a552;
}
.activeLink {
  font-weight: bold;
}
</style>