当前位置:首页 > VUE

vue实现导航栏高亮

2026-02-24 09:04:34VUE

Vue 实现导航栏高亮的方法

动态绑定 class

通过 v-bind:class 或简写 :class 动态绑定高亮样式,结合当前路由或状态判断是否激活。

<template>
  <nav>
    <router-link 
      to="/home" 
      :class="{ 'active': $route.path === '/home' }"
    >Home</router-link>
    <router-link 
      to="/about" 
      :class="{ 'active': $route.path === '/about' }"
    >About</router-link>
  </nav>
</template>

<style>
.active {
  color: #42b983;
  font-weight: bold;
}
</style>

使用 Vue Router 的 exact-active-class

Vue Router 内置 exact-active-class 属性,可自动匹配精确路由。

<router-link 
  to="/home" 
  exact-active-class="active"
>Home</router-link>

计算属性判断

通过计算属性返回高亮状态,适用于复杂条件。

<template>
  <nav>
    <a @click="navigate('/home')" :class="{ active: isActive('/home') }">Home</a>
    <a @click="navigate('/about')" :class="{ active: isActive('/about') }">About</a>
  </nav>
</template>

<script>
export default {
  methods: {
    navigate(path) {
      this.$router.push(path);
    },
    isActive(path) {
      return this.$route.path === path;
    }
  }
};
</script>

使用 CSS 伪类

结合 Vue Router 的 router-link 和 CSS 伪类实现高亮。

<router-link to="/home" class="nav-link">Home</router-link>
<router-link to="/about" class="nav-link">About</router-link>

<style>
.router-link-exact-active.nav-link {
  color: #42b983;
  border-bottom: 2px solid #42b983;
}
</style>

嵌套路由高亮

处理嵌套路由时,使用 $route.matched 检查路径层级。

vue实现导航栏高亮

<template>
  <a :class="{ active: isActive('/products') }">Products</a>
</template>

<script>
export default {
  methods: {
    isActive(path) {
      return this.$route.matched.some(route => route.path === path);
    }
  }
};
</script>

注意事项

  • 动态绑定 class 时,确保样式优先级足够覆盖默认样式。
  • 使用 exact-active-class 时,若需模糊匹配(如子路由),改用 active-class
  • 对于非路由导航,可通过状态管理(如 Vuex)存储当前激活项。

标签: vue高亮
分享给朋友:

相关文章

vue tag实现

vue tag实现

Vue 标签实现方法 在 Vue 中实现标签功能可以通过多种方式完成,常见场景包括动态标签生成、标签输入框、标签管理等。以下是几种典型实现方案: 动态标签列表渲染 使用 v-for 指令渲染标签数组…

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装…

vue实现甘特图

vue实现甘特图

使用 Vue 实现甘特图 基于开源库(如 vue-ganttastic) 安装依赖库: npm install vue-ganttastic 示例代码: <template> &l…

mui实现vue

mui实现vue

mui 实现 Vue 的步骤 mui 是一个轻量级的前端框架,常用于移动端开发。结合 Vue 可以实现高效的开发体验。以下是具体实现方法。 安装 mui 和 Vue 通过 npm 或 yarn 安装…

vue实现秒表

vue实现秒表

实现秒表功能 在Vue中实现秒表功能需要处理时间显示、开始、暂停和重置逻辑。以下是具体实现方式: 基础实现代码 <template> <div> <div&…