vue

Vue3--篇19--自定义 hook 函数

2023-04-21  本文已影响0人  扶得一人醉如苏沐晨

自定义 hook 函数

实现一个功能点击页面获取点击的坐标轴

<template>
  <h1>x轴坐标{{ point.x }}</h1>
  <h1>y轴坐标{{ point.y }}</h1>
  <button @click="getPoint">获取点击的坐标</button>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
export default {
  name: "App",
  setup() {
    let point = reactive({
      x: 0,
      y: 0,
    });
    function getPoint(event) {
      point.x = event.pageX;
      point.y = event.pageY;
    }
    onMounted(() => {
      window.addEventListener("click", getPoint);
    });
    onBeforeUnmount(() => {
      window.addEventListener("click", getPoint);
    });
    return {
      point,
      getPoint,
    };
  },
};
</script>

<style lang="scss"></style>

封装hooks

import { reactive, onMounted, onBeforeUnmount } from "vue";
export default function () {
  let point = reactive({
    x: 0,
    y: 0,
  });
  function getPoint(event) {
    point.x = event.pageX;
    point.y = event.pageY;
  }
  onMounted(() => {
    window.addEventListener("click", getPoint);
  });
  onBeforeUnmount(() => {
    window.addEventListener("click", getPoint);
  });
  return point;
}

<template>
  <h1>x轴坐标{{ point.x }}</h1>
  <h1>y轴坐标{{ point.y }}</h1>
</template>

<script>
import getPoint from "./components/hooks/getPoint";
export default {
  name: "App",
  setup() {
    let point = getPoint();
    return {
      point,
    };
  },
};
</script>

<style lang="scss"></style>

上一篇 下一篇

猜你喜欢

热点阅读