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

Nuxt 3 Router刷新页面无法检测哈希值的问题求助

解决NuxtLink哈希路由刷新后active类错误的问题

问题根源

你之前用router.currentRoute.value.href拿到的是带域名的完整URL(比如http://localhost:3000/#search),但菜单里的item.href是相对路径(比如/#search),两者字符串完全不匹配,导致手动绑定的active类无法生效。同时NuxtLink默认会按路由path部分匹配添加active类,当路径是/#search时,path仍为/,所以Home链接会被错误激活。

修正方案

  1. 改用路由path + hash的组合和菜单相对路径对比,保证字符串完全匹配
  2. 给NuxtLink加上exact属性,避免默认的部分匹配逻辑干扰

修改后的完整代码

<template>
    <nav>
        <NuxtLink 
            v-for="item in menu" 
            :key="item.href" 
            :to="item.href"
            exact
            :class="['menu-c--nav--link', {'active': item.href === activeMenuPath}]"
        >
            {{ item.text }}
        </NuxtLink>
    </nav>
</template>

<script setup lang="ts">
import MenuInterface from "@contracts/MenuInterface";

const menu: MenuInterface[] = [
    {href: '/', text: 'Home'},
    {href: '/#search', text: 'Search'},
    {href: '/#about', text: 'About'},
    {href: '/#certificates', text: 'Certificates'},
    {href: '/#gallery', text: 'Gallery'},
    {href: '/#proposals', text: 'Proposals'},
]

const router = useRouter()
const activeMenuPath: Ref<string | null> = ref(null)

watchEffect(() => {
    const { path, hash } = router.currentRoute.value
    // 拼接path和hash,得到和菜单item.href一致的相对路径格式
    activeMenuPath.value = path + hash
})
</script>

额外说明

  • watchEffect会在组件初始化和路由变化时自动执行,确保页面刷新时能立刻获取到正确的path+hash组合
  • exact属性让NuxtLink只有在路径完全匹配时才会添加默认active类,避免Home链接因为path=/就被错误激活
  • 如果不想用NuxtLink的默认active类,可以额外添加active-class=""属性禁用它,完全使用自定义的active类逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:27:33