Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useElementHover): add options to the directive #3897

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/core/useElementHover/demo.vue
@@ -1,13 +1,21 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useElementHover } from '@vueuse/core'
import { vElementHover } from './directive'

const el = ref<HTMLButtonElement>()
const isDirectiveHovered = ref(false)
const isHovered = useElementHover(el, { delayEnter: 200, delayLeave: 600 })
function onHover(hovered: boolean) {
isDirectiveHovered.value = hovered
}
</script>

<template>
<button ref="el">
<span>{{ isHovered ? 'Thank you!' : 'Hover me' }}</span>
</button>
<button v-element-hover="[onHover, { delayEnter: 200, delayLeave: 600 }]">
<span>{{ isDirectiveHovered ? 'Thank you!' : 'Hover me' }}</span>
</button>
</template>
15 changes: 11 additions & 4 deletions packages/core/useElementHover/directive.ts
@@ -1,18 +1,25 @@
import { watch } from 'vue-demi'
import { directiveHooks } from '@vueuse/shared'
import type { ObjectDirective } from 'vue-demi'
import type { UseElementHoverOptions } from '.'
import { useElementHover } from '.'

type BindingValueFunction = (state: boolean) => void

export const vElementHover: ObjectDirective<
HTMLElement,
BindingValueFunction
HTMLElement,
BindingValueFunction | [handler: BindingValueFunction, options: UseElementHoverOptions]
> = {
[directiveHooks.mounted](el, binding) {
if (typeof binding.value === 'function') {
const value = binding.value
if (typeof value === 'function') {
const isHovered = useElementHover(el)
watch(isHovered, v => binding.value(v))
watch(isHovered, v => value(v))
}
else {
const [handler, options] = value
const isHovered = useElementHover(el, options)
watch(isHovered, v => handler(v))
}
},
}
20 changes: 20 additions & 0 deletions packages/core/useElementHover/index.md
Expand Up @@ -42,3 +42,23 @@ function onHover(state: boolean) {
</button>
</template>
```

You can also provide hover options:

```vue
<script setup lang="ts">
import { ref } from 'vue'
import { vElementHover } from '@vueuse/components'

const isHovered = ref(false)
function onHover(hovered: boolean) {
isHovered.value = hovered
}
</script>

<template>
<button v-element-hover="[onHover, { delayEnter: 1000 }]">
<span>{{ isHovered ? 'Thank you!' : 'Hover me' }}</span>
</button>
</template>
```