I would like to show a div when hovering over an element in vue.js. But I can\'t seem to get it working.
It looks like there is no event for hover or mouseover in vue.j
Though I would give an update using the new composition api.
{{ hovering }}
Creating a useHover
function will allow you to reuse in any components.
export function useHover(target: Ref) {
const hovering = ref(false)
const enterHandler = () => (hovering.value = true)
const leaveHandler = () => (hovering.value = false)
onMounted(() => {
if (!target.value) return
target.value.addEventListener('mouseenter', enterHandler)
target.value.addEventListener('mouseleave', leaveHandler)
})
onUnmounted(() => {
if (!target.value) return
target.value.removeEventListener('mouseenter', enterHandler)
target.value.removeEventListener('mouseleave', leaveHandler)
})
return hovering
}
Here's a quick example calling the function inside a Vue component.
{{ hovering }}
You can also use a library such as @vuehooks/core which comes with many useful functions including useHover
.