Vue3模块化妙用初体验

2022-09-08 18:06:51 浏览数 (1)

如下需求

当鼠标点击的时候,记录当前点击的坐标(x,y)用vue3实现

代码语言:javascript复制
<template>
  <img alt="Vue logo" src="./assets/logo.png">
   <h1>X:{{x}}</h1>
   <h2>Y:{{y}}</h2>
</template>

<script lang="ts">
import {ref,onMounted,onUnmounted} from 'vue';
export default {
 setup(){
    const x = ref(0)
    const y = ref(0)
    const updateMouse = (e: MouseEvent)=>{
      x.value = e.pageX
      y.value = e.pageY
    }
    onMounted(()=>{
      document.addEventListener("click",updateMouse)
    })
    onUnmounted(()=>{
      document.removeEventListener("click",updateMouse)
    })
    return{
      x,y
    }

 }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

至此我们已经实现鼠标点击时更新坐标,接下来我们将记录坐标这部分逻辑抽离出来,可能其他页面也需要记录坐标

新建模块文件 src/hooks/useMousePosition.ts

代码语言:javascript复制
import {ref,onMounted,onUnmounted} from 'vue';

/**
 * 记录鼠标坐标
 */
function updateMouse(){
    const x = ref(0)
    const y = ref(0)
    const updateMouse = (e: MouseEvent)=>{
        x.value = e.pageX
        y.value = e.pageY
    }
    onMounted(()=>{
        document.addEventListener("click",updateMouse)
    })
    onUnmounted(()=>{
        document.removeEventListener("click",updateMouse)
    })
    return{
        x,y
    }
}

export default updateMouse

在App.vue导入

代码语言:javascript复制
<script lang="ts">
import {ref,onMounted,onUnmounted} from 'vue';
import useMousePosition from './hooks/useMousePosition'
export default {
 setup(){
    const {x,y} = useMousePosition()
    return{
      x,y
    }

 }
}
</script>

这样一个记录鼠标位置的逻辑就被我们抽离出来

0 人点赞