You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Router-Link的active-class不识别哈希/查询参数的问题解决

我遇到的问题是:当用户访问包含哈希(#)或查询参数(?xxx)的精确路径时,无法给router-link添加正确的激活样式。原因是Vue Router的active-class和exact-active-class默认不会识别哈希或查询参数,而且Vue3已经移除了旧版的exact属性。

解决方案:自定义激活判断逻辑

通过结合Vue Router的$route对象,手动判断当前路径是否完全匹配(包括哈希和查询参数),然后动态绑定样式类。

方法1:直接在router-link上绑定计算属性

<router-link
  :to="{ path: '/page', hash: '#section', query: { id: 1 } }"
  :class="{ 'active-link': isExactActive }"
>
  带参数的页面链接
</router-link>

<script setup>
import { useRoute, computed } from 'vue-router'

const route = useRoute()

const isExactActive = computed(() => {
  // 匹配完整路径:路径+哈希+查询参数
  return route.fullPath === '/page#section?id=1'
})
</script>

<style>
.active-link {
  color: #42b983;
  font-weight: bold;
  border-bottom: 2px solid #42b983;
}
</style>

方法2:封装成可复用组件

如果多个链接需要这个逻辑,可以封装成自定义组件:

<!-- ExactRouterLink.vue -->
<template>
  <router-link
    :to="to"
    :class="{ [activeClass]: isExactActive }"
    v-bind="$attrs"
  >
    <slot></slot>
  </router-link>
</template>

<script setup>
import { useRoute, computed } from 'vue-router'

const props = defineProps({
  to: {
    type: [String, Object],
    required: true
  },
  activeClass: {
    type: String,
    default: 'active-link'
  }
})

const route = useRoute()

const isExactActive = computed(() => {
  // 处理字符串形式的to
  if (typeof props.to === 'string') {
    return route.fullPath === props.to
  }
  // 处理对象形式的to,拼接成完整路径
  const { path = '', hash = '', query = {} } = props.to
  const queryStr = new URLSearchParams(query).toString()
  const fullToPath = `${path}${hash}${queryStr ? `?${queryStr}` : ''}`
  return route.fullPath === fullToPath
})
</script>

使用时直接调用:

<ExactRouterLink :to="{ path: '/page', hash: '#section', query: { id: 1 } }">
  带参数的页面链接
</ExactRouterLink>

补充说明

这种方式完全由我们控制匹配逻辑,不仅能识别哈希和查询参数,还能根据需求调整匹配规则(比如忽略某个查询参数),比依赖exact-active-class更灵活。

内容的提问来源于stack exchange,提问作者Devlos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:01:01