mouseHook vue 鼠标移动hook

2020-04-09 11:49:54 浏览数 (1)

chart.gif

使用例子
代码语言:javascript复制
<template>
  <div class="home" ref='element'>

    <div ref='hoverEle' >
      <Card style='margin: 20% auto; width: 600px' title='' >
        
        <div v-for='(value, key) of state' :key='key'>
          {{ key }} : {{ value }}
        </div>

      </Card>
    </div>
    
  </div>
</template>

<script>
// import { ref } from '@vue/composition-api'
import mouseHook from '@/hooks/mouseHook'

export default { 

  setup(){
 
    const state = mouseHook()
   
    return {
      
      state
      
    }
    

  }

}
</script>
实现
代码语言:javascript复制
import { ref, onMounted, onUnmounted } from '@vue/composition-api'


/**
 * 鼠标移动监听 hook
 * @returns { ref } state 数据对象
 * 
 */
export default function mouseHook(){
    const state = ref({})
    

    const moveHandler = event => {

        const { screenX, screenY, clientX, clientY, pageX, pageY } = event;
        state.value = { screenX, screenY, clientX, clientY, pageX, pageY }

    }
    
    onMounted(() => {
        document.addEventListener('mousemove', moveHandler)
    })
    
    onUnmounted(() =>{
        document.removeEventListener('mousemove', moveHandler)
    })


    return state
    
}
gif

0 人点赞