feat(Link): allow partial query match for activeClass (#2663)

This commit is contained in:
Sandro Circi
2024-11-17 12:15:22 +01:00
committed by GitHub
parent d0e626c551
commit 03e24f4583
2 changed files with 18 additions and 5 deletions

View File

@@ -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.

View File

@@ -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({
@@ -61,7 +61,7 @@ export default defineComponent({
default: false
},
exactQuery: {
type: Boolean,
type: [Boolean, String] as PropType<boolean | 'partial'>,
default: false
},
exactHash: {
@@ -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