Skip to content

Commit

Permalink
feat(useElementHover): directive support (#1359)
Browse files Browse the repository at this point in the history
  • Loading branch information
webfansplz committed Mar 5, 2022
1 parent f39e5e4 commit 73b0def
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
42 changes: 42 additions & 0 deletions packages/core/useElementHover/directive.test.ts
@@ -0,0 +1,42 @@
import { defineComponent } from 'vue-demi'
import type { VueWrapper } from '@vue/test-utils'
import { mount } from '@vue/test-utils'

import { vElementHover } from './directive'

const App = defineComponent({
props: {
onHover: {
type: Function,
required: true,
},
},

template: `<template>
<div v-element-hover="onHover">Hover me</div>
</template>
`,
})

describe('vElementHover', () => {
let onHover = vi.fn()
let wrapper: VueWrapper<any>

beforeEach(() => {
onHover = vi.fn()
wrapper = mount(App, {
props: {
onHover,
},
global: {
directives: {
elementHover: vElementHover,
},
},
})
})

it('should be defined', () => {
expect(wrapper).toBeDefined()
})
})
15 changes: 15 additions & 0 deletions packages/core/useElementHover/directive.ts
@@ -0,0 +1,15 @@
import { watch } from 'vue-demi'
import type { FunctionDirective } from 'vue-demi'
import { useElementHover } from '.'

type BindingValueFunction = (state: boolean) => void

export const vElementHover: FunctionDirective<
HTMLElement,
BindingValueFunction
> = (el, binding) => {
if (typeof binding.value === 'function') {
const isHovered = useElementHover(el)
watch(isHovered, v => binding.value(v))
}
}
24 changes: 24 additions & 0 deletions packages/core/useElementHover/index.md
Expand Up @@ -8,6 +8,8 @@ Reactive element's hover state.

## Usage

### As a hook

```vue
<template>
<button ref="myHoverableElement">
Expand All @@ -22,3 +24,25 @@ const myHoverableElement = ref()
const isHovered = useElementHover(myHoverableElement)
</script>
```
### As a directive

<LearnMoreComponents />

```html
<script setup lang="ts">
import { ref } from 'vue'
import { vElementHover } from '@vueuse/components'
const isHovered = ref(false)
function onHover(state: boolean) {
isHovered.value = state
}
</script>

<template>
<button v-element-hover="onHover">
{{ isHovered ? 'Thank you!' : 'Hover me' }}
</button>
</template>

```

0 comments on commit 73b0def

Please sign in to comment.