Skip to content

Commit 4c865b1

Browse files
committed
fix(theme-default): make navlink active in subpath (close #70)
1 parent 4b8d0cf commit 4c865b1

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

packages/@vuepress/theme-default/src/components/NavLink.vue

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
<RouterLink
33
v-if="isRouterLink"
44
class="nav-link"
5+
:class="{ 'router-link-active': isActiveInSubpath }"
56
:to="item.link"
6-
:exact="isExact"
77
:aria-label="linkAriaLabel"
88
v-bind="$attrs"
99
>
@@ -30,6 +30,7 @@
3030
<script lang="ts">
3131
import { computed, defineComponent, toRefs } from 'vue'
3232
import type { PropType } from 'vue'
33+
import { useRoute } from 'vue-router'
3334
import { useSiteData } from '@vuepress/client'
3435
import { isLinkHttp, isLinkMailto, isLinkTel } from '@vuepress/shared'
3536
import type { NavLink } from '../types'
@@ -47,6 +48,7 @@ export default defineComponent({
4748
},
4849
4950
setup(props) {
51+
const route = useRoute()
5052
const site = useSiteData()
5153
const { item } = toRefs(props)
5254
@@ -72,14 +74,6 @@ export default defineComponent({
7274
!hasNonHttpProtocal.value &&
7375
!isBlankTarget.value
7476
)
75-
// is the `exact` prop of `<RouterLink>` should be true
76-
const isExact = computed(() => {
77-
const localeKeys = Object.keys(site.value.locales)
78-
if (localeKeys.length) {
79-
return localeKeys.some((key) => key === item.value.link)
80-
}
81-
return item.value.link === '/'
82-
})
8377
// resolve the `rel` attr
8478
const linkRel = computed(() => {
8579
if (hasNonHttpProtocal.value) return undefined
@@ -92,9 +86,25 @@ export default defineComponent({
9286
() => item.value.ariaLabel || item.value.text
9387
)
9488
89+
// should be active when current route is a subpath of this link
90+
const shouldBeActiveInSubpath = computed(() => {
91+
const localeKeys = Object.keys(site.value.locales)
92+
if (localeKeys.length) {
93+
return !localeKeys.some((key) => key === item.value.link)
94+
}
95+
return item.value.link !== '/'
96+
})
97+
// if this link is active in subpath
98+
const isActiveInSubpath = computed(() => {
99+
if (!isRouterLink.value || !shouldBeActiveInSubpath.value) {
100+
return false
101+
}
102+
return route.path.startsWith(item.value.link)
103+
})
104+
95105
return {
106+
isActiveInSubpath,
96107
isBlankTarget,
97-
isExact,
98108
isRouterLink,
99109
linkRel,
100110
linkTarget,

packages/@vuepress/theme-default/src/styles/navbar.scss

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ $navbar-horizontal-padding: 1.5rem;
6969
display: inline-block;
7070

7171
a {
72+
display: inline-block;
7273
line-height: 1.4rem;
7374
color: inherit;
7475

0 commit comments

Comments
 (0)