【15.0】Vue之Hook实现打点

【一】JS代码

  • \src\hook\UsePoint.js
import {onBeforeUnmount, onMounted, reactive} from "vue";

export default function () {
    let point = reactive({
        x: 0,
        y: 0
    })

    function getPoint(event) {
        console.log(event.pageX)
        console.log(event.pageY)
        point.x = event.pageX
        point.y = event.pageY
    }

    // 挂在完成开始执行
    onMounted(() => {
        window.addEventListener('click', getPoint)
    })
    // 接除挂载时执行
    onBeforeUnmount(() => {
        console.log('sss')
        window.removeEventListener('click', getPoint)
    })
    return point
}

【二】PointView

  • src\components\PointView.vue
<script setup>

</script>

<template>
  <div>
    <hr>
    <h2>x坐标:>>>>{{ point.x }}</h2>
    <hr>
    <h2>y坐标:>>>>{{ point.y }}</h2>
    <hr>
  </div>
</template>
<script>
import {onBeforeUnmount, onMounted, reactive, toRefs} from "vue";
import UsePoint from "@/hook/UsePoint";

export default {
  name: 'PointView',
  setup() {
    let point = UsePoint()
    console.log(point)
    return {point}
  }
}
</script>
<style scoped>

</style>

【三】HomeView

  • src\views\HomeView.vue
<script setup>
</script>

<template>
  <div>
    <h1>这是一个坐标信息</h1>

    <button @click="showFunc">点我启用/关闭</button>
    <br>
    <PointView v-if="show"></PointView>

  </div>
</template>

<script>
// 导入ref函数
import {ref, reactive, toRefs, onMounted, onBeforeUnmount} from "vue";
// 导入reactive函数
import PointView from "@/components/PointView.vue";

export default {

  name: "HomeView",
  components: {
    PointView,
  },
  setup() {
    let show = ref(true);
    const showFunc = () => {
      show.value = !show.value;
    }
    return {show, showFunc}
  }

}
</script>
posted @ 2023-08-07 08:28  Chimengmeng  阅读(32)  评论(0编辑  收藏  举报