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

Vue3+Vuetify3中同路由不同查询参数的菜单选中状态问题

解决Vuetify v3中同路径不同查询参数的菜单激活冲突问题

Vuetify的v-list-item默认路由匹配逻辑仅校验路径部分,忽略查询参数,这就导致指向/threads和/threads?by=lucien的两个菜单会同时被标记为激活状态。要让它们成为独立的菜单项,你可以通过手动控制active属性来实现精确匹配。

方法一:直接绑定激活判断逻辑

通过vue-router的useRoute获取当前路由,给每个v-list-item绑定active属性,结合路径和查询参数判断是否激活:

<template>
  <v-navigation-drawer>
    <v-list nav>
      <v-list-item 
        title="Threads" 
        value="threads" 
        to="/threads" 
        link
        :active="route.path === '/threads' && !route.query.by"
      />
      <v-list-item 
        title="My Threads" 
        value="myThreads" 
        to="/threads?by=lucien" 
        link
        :active="route.path === '/threads' && route.query.by === 'lucien'"
      />
      <v-list-item 
        title="Another Menu" 
        value="anotherMenu" 
        to="/another" 
        link
      />
      ...
    </v-list>
  </v-navigation-drawer>
</template>

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

const route = useRoute()
</script>

方法二:封装通用激活判断函数

如果有多个类似的菜单项,可封装一个通用函数来简化代码,统一处理路径和查询参数的匹配逻辑:

<template>
  <v-navigation-drawer>
    <v-list nav>
      <v-list-item 
        title="Threads" 
        value="threads" 
        to="/threads" 
        link
        :active="isActive('/threads', { by: null })"
      />
      <v-list-item 
        title="My Threads" 
        value="myThreads" 
        to="/threads?by=lucien" 
        link
        :active="isActive('/threads', { by: 'lucien' })"
      />
      <v-list-item 
        title="Another Menu" 
        value="anotherMenu" 
        to="/another" 
        link
      />
      ...
    </v-list>
  </v-navigation-drawer>
</template>

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

const route = useRoute()

const isActive = (targetPath, targetQuery) => {
  if (route.path !== targetPath) return false
  
  return Object.entries(targetQuery).every(([key, value]) => {
    // 若目标参数为null,则检查当前路由是否无该参数
    if (value === null) {
      return !route.query[key]
    }
    return route.query[key] === value
  })
}
</script>

原理说明

通过手动控制active属性,我们覆盖了Vuetify默认的路由匹配规则,加入了查询参数的校验条件,确保只有当路径和指定查询参数完全匹配时,对应的菜单项才会被标记为激活状态,从而实现两个菜单的独立激活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:43:00