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

如何在Vuetify.js中为可展开列表添加激活状态?

在Vuetify中为导航列表添加激活状态

要实现和Vuetify官方文档一致的「激活项显示primary背景色」效果,你可以结合Vue Router的路由状态,用两种简单方式处理:

方法一:用Vuetify内置路由匹配(推荐)

Vuetify的v-list-item原生支持:to属性,它会自动监听路由变化,当路由匹配时自动给激活项添加样式,无需手动判断逻辑:

修改你的子列表项代码:

<v-list-item 
  v-for="(subItem, i) in item.children" 
  :key="i" 
  :to="subItem.path"
  color="primary"
  <!-- 若需完全匹配路由(避免子路由误激活父项),添加此属性 -->
  :exact="true"
>
  <v-list-item-content>
    <v-list-item-title v-text="subItem.title"></v-list-item-title>
  </v-list-item-content>
</v-list-item>
  • 把原有的@click="$router.push(subItem.path)"替换成:to="subItem.path",Vuetify会同时处理路由跳转和激活状态。
  • color="primary"会让激活项的背景色直接使用主题的primary配色,和官方文档效果一致。
  • 如果你的路由存在层级嵌套(比如/dashboard和/dashboard/detail),:exact="true"能确保只有完全匹配路径时才激活对应项。

方法二:手动判断路由状态

如果你更习惯保留@click的跳转方式,可以通过$route对象手动匹配路由,给v-list-item添加:active属性:

<v-list-item 
  v-for="(subItem, i) in item.children" 
  :key="i" 
  @click="$router.push(subItem.path)"
  :active="$route.path === subItem.path"
  color="primary"
>
  <v-list-item-content>
    <v-list-item-title v-text="subItem.title"></v-list-item-title>
  </v-list-item-content>
</v-list-item>

这里通过$route.path === subItem.path判断当前路由是否与子项路径一致,匹配时就会激活该列表项,显示primary背景色。

额外优化:父级列表组随子项激活自动展开

如果希望子项激活时,对应的父级v-list-group自动展开并显示激活样式,给v-list-group添加:active属性即可:

<v-list-group 
  v-for="(item, i) in items" 
  :key="i" 
  no-action 
  color="primary"
  :active="item.children.some(subItem => $route.path.includes(subItem.path))"
>
  <!-- 激活器和子项内容 -->
</v-list-group>

通过item.children.some(...)判断当前路由是否包含任一子项的路径,匹配时就会激活并展开该列表组。

这样修改后,你的导航列表就能和官方文档一样,当前路由对应的项会自动显示primary背景色的激活状态啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:22:49