Skip to content

Commit

Permalink
fix(Link): handle isActive through vue-router
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamincanac committed Feb 23, 2022
1 parent 09aed4b commit aef1156
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions src/runtime/components/elements/Link.vue
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
<template>
<button v-if="isButton" v-bind="$attrs" :class="isActive ? activeClass : inactiveClass">
<slot v-bind="{ isActive }" />
<button v-if="isButton" v-bind="$attrs" :class="inactiveClass">
<slot />
</button>
<a v-else-if="isExternalLink" v-bind="$attrs" :class="isActive ? activeClass : inactiveClass" :href="to" :target="target">
<slot v-bind="{ isActive }" />
<a v-else-if="isExternalLink" v-bind="$attrs" :class="inactiveClass" :href="to" :target="target">
<slot />
</a>
<router-link
v-else
v-slot="{ href, navigate }"
v-slot="{ href, navigate, isActive, isExactActive }"
v-bind="$props"
custom
>
<a
v-bind="$attrs"
:href="href"
:class="isActive ? activeClass : inactiveClass"
:class="resolveLinkClass({ isActive, isExactActive })"
@click="navigate"
>
<slot v-bind="{ isActive }" />
Expand All @@ -25,7 +25,6 @@
<script>
import { computed } from 'vue'
import { RouterLink } from 'vue-router'
import { useRoute } from '#imports'
export default {
name: 'Link',
Expand All @@ -50,29 +49,25 @@ export default {
}
},
setup (props) {
const route = useRoute()
const isActive = computed(() => {
if (!props.to) {
return false
}
if (props.exact) {
return [props.to, `${props.to}/`].includes(route.path)
} else {
return !!route.path.startsWith(props.to)
}
})
const isExternalLink = computed(() => {
return typeof props.to === 'string' && props.to.startsWith('http')
})
const isButton = computed(() => {
return !props.to
})
function resolveLinkClass ({ isActive, isExactActive }) {
if ((props.exact && isExactActive) || isActive) {
return props.activeClass
} else {
return props.inactiveClass
}
}
return {
isActive,
isButton,
isExternalLink
isExternalLink,
resolveLinkClass
}
}
}
Expand Down

1 comment on commit aef1156

@vercel
Copy link

@vercel vercel bot commented on aef1156 Feb 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

Please sign in to comment.