Mouseover or hover vue.js

前端 未结 13 1677
温柔的废话
温柔的废话 2021-01-30 02:13

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

13条回答
  •  孤街浪徒
    2021-01-30 02:29

    Though I would give an update using the new composition api.

    Component

    
    
    
    

    Reusable Composition Function

    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.

    
    
    
    

    You can also use a library such as @vuehooks/core which comes with many useful functions including useHover.

提交回复
热议问题