Vue 3 路由器 - router-link-active 不起作用

问题描述 投票:0回答:2

在带有路由器 4 的 vue 3 中,类

router-link-active
不再为我工作。如果您与
router-link-exact-active
位于同一页面上,则该类会出现,但不位于任何子页面上。

例如,链接

<router-link :to="{ name: 'test'}">test</router-link>
获取的是
/test
上的类
router-link-active
router-link-exact-active,但在/test/2

上没有一个类
{
    path: '/test',
    name: 'test',
    component: Test
},
{
    path: '/test/2',
    name: 'test-2',
    component: Test2
},

真实例子: https://codesandbox.io/s/vue-router-4-reproductive-forked-zcb7y

谢谢,任何想法或建议

vue.js vue-router vuejs3 vue-router4
2个回答
24
投票

我错过了https://github.com/vuejs/rfcs/blob/master/active-rfcs/0028-router-active-link.md#unrelated-but-similiar-routes,它有点隐藏。显示的 RouterView 解决方法工作正常。这是我的例子:

import { h } from 'vue'
import { RouterView } from 'vue-router'

const routes = [
  {
    path: '/test',
    component: { render: () => h(RouterView) },
    children: [
      { 
        path: '',
        name: 'test',
        component: Test
      },
      { 
        path: '2',
        name: 'test-2',
        component: Test2
      }
    ]
  }
]

0
投票

我在这里遇到了一个问题,结果是由于在路由文件中声明了两次路由而导致

<router-link>
使用了路由文件中的第二个声明,因此当您使用时
active
属性不起作用单击该链接,但如果您在页面上重新加载页面,它就会起作用。

这是真的,因为当您重新加载页面时,由于 vue-router 加载了第一个匹配的路由,因此匹配了正确的路由。

在我更改路由器链接以使用正确的路由并删除重复的路由后。

我的情况有点奇怪,因为它以某种方式起作用,代码中几乎没有证据,直到我开始将

useRoute().name
记录到屏幕上,我注意到它有一个不同/不正确的名称。

作为奖励,我发现这篇文章对于确认一切都按预期工作非常有帮助:https://github.com/vuejs/rfcs/blob/master/active-rfcs/0028-router-active-link。 md#不相关但相似的路线

© www.soinside.com 2019 - 2024. All rights reserved.