Skip to content

Commit

Permalink
feat(Link): allow partial query match for activeClass (#2663)
Browse files Browse the repository at this point in the history
  • Loading branch information
sandros94 authored Nov 17, 2024
1 parent d0e626c commit 03e24f4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
1 change: 1 addition & 0 deletions docs/content/2.components/link.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ The Link component is a wrapper around [`<NuxtLink>`](https://nuxt.com/docs/api/
- `inactive-class` prop to set a class when the link is inactive, `active-class` is used when active.
- `exact` prop to style with `active-class` when the link is active and the route is exactly the same as the current route.
- `exact-query` and `exact-hash` props to style with `active-class` when the link is active and the query or hash is exactly the same as the current query or hash.
- use `exact-query="partial"` to style with `active-class` when the link is active and the query partially match the current query.

The incentive behind this is to provide the same API as NuxtLink back in Nuxt 2 / Vue 2. You can read more about it in the Vue Router [migration from Vue 2](https://router.vuejs.org/guide/migration/#removal-of-the-exact-prop-in-router-link) guide.

Expand Down
22 changes: 17 additions & 5 deletions src/runtime/components/elements/Link.vue
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
</template>

<script lang="ts">
import { isEqual } from 'ohash'
import { defineComponent } from 'vue'
import { isEqual, diff } from 'ohash'
import { type PropType, defineComponent } from 'vue'
import { nuxtLinkProps } from '../../utils'
export default defineComponent({
Expand Down Expand Up @@ -61,7 +61,7 @@ export default defineComponent({
default: false
},
exactQuery: {
type: Boolean,
type: [Boolean, String] as PropType<boolean | 'partial'>,
default: false
},
exactHash: {
Expand All @@ -74,9 +74,21 @@ export default defineComponent({
}
},
setup(props) {
function isPartiallyEqual(item1, item2) {
const diffedKeys = diff(item1, item2).reduce((filtered, q) => {
if (q.type === 'added') {
filtered.push(q.key)
}
return filtered
}, [])
return isEqual(item1, item2, { excludeKeys: key => diffedKeys.includes(key) })
}
function resolveLinkClass(route, $route, { isActive, isExactActive }: { isActive: boolean, isExactActive: boolean }) {
if (props.exactQuery && !isEqual(route.query, $route.query)) {
return props.inactiveClass
if (props.exactQuery === 'partial') {
if (!isPartiallyEqual(route.query, $route.query)) return props.inactiveClass
} else if (props.exactQuery === true) {
if (!isEqual(route.query, $route.query)) return props.inactiveClass
}
if (props.exactHash && route.hash !== $route.hash) {
return props.inactiveClass
Expand Down

0 comments on commit 03e24f4

Please sign in to comment.