美文网首页
hoverHook vue 鼠标悬浮 Hook

hoverHook vue 鼠标悬浮 Hook

作者: copyLeft | 来源:发表于2020-04-07 12:18 被阅读0次

    使用例子

    chart.gif
    <template>
      <div class="home" ref='element'>
    
        <div ref='hoverEle' >
          <Card style='margin: 20% auto; width: 600px' title='' >
            {{ isHover }}
          </Card>
        </div>
        
      </div>
    </template>
    
    <script>
    // import { ref } from '@vue/composition-api'
    import hoverHook from '@/hooks/hoverHook'
    
    export default { 
    
      setup(){
     
        const [ isHover, hoverEle ] = hoverHook({
          onEnter(e){ console.log('enter >>>', e) },
          onLeave(e){ console.log('leave >>>', e) },
        })
       
        return {
          
          isHover,
          hoverEle
          
        }
        
    
      }
    
    }
    </script>
    
    

    实现

    import { ref, watch, computed } from '@vue/composition-api'
    import boolHook from './boolHook'
    
    
    /**
     * dom 鼠标悬浮事件 hook
     * @param { { dom, onEnter, onLeave } } options 配置  dom 初始绑定dom  onEnter 滑出事件 onLeave 滑出事件 
     * @returns { [ state, element ] } state 滑入状态  element dom绑定ref
     * 
     * @example
     * 
     *  setup
     *  
     *  const [ isHover, hoverEle ] = hoverHook({
          onEnter(e){ console.log('enter >>>', e) },
          onLeave(e){ console.log('leave >>>', e) },
        })
     *
     *  模板
     * 
     *  <div ref='hoverEle' >
          <Card style='margin: 20% auto; width: 600px' title='' >
            {{ isHover }}
          </Card>
        </div>
     *  
     */
    
    export default function hoverHook(options={}){
        const { dom, onEnter, onLeave } = options
        const element = ref(null)
        const onEnterRef = ref(onEnter)
        const onLeaveRef = ref(onLeave)
    
        const { state, setTrue, setFalse } = boolHook(false)
    
        const targetElement = computed(() => {
            const ele = dom ? dom.value : element.value
            return ele || element.value
        })
        
        const onMouseEnter = () => {
            onEnterRef.value && onEnterRef.value()
            setTrue()
        }
    
        const onMouseLeave = () => {
            onLeaveRef.value && onLeaveRef.value()
            setFalse()
        }
        
        
        watch(() => targetElement.value, (val, oldVal) =>{
    
            if(oldVal){
                oldVal.removeEventListener('mouseenter', onMouseEnter);
                oldVal.removeEventListener('mouseleave', onMouseLeave);
            }
            
            if(val){
                val.addEventListener('mouseenter', onMouseEnter);
                val.addEventListener('mouseleave', onMouseLeave);
            }
    
        })
        
    
        return [ state, element ]
        
    }
    

    相关文章

      网友评论

          本文标题:hoverHook vue 鼠标悬浮 Hook

          本文链接:https://www.haomeiwen.com/subject/oxigphtx.html