# Hook

# 简单的例子

我们来实现一个功能,将当前鼠标点击的坐标位置显示到界面上

<script setup>
import { onBeforeMount, onMounted, reactive } from "vue";

let point = reactive({
  x: 0,
  y: 0
});

const handleWindowClick = (e) => {
  point.x = e.pageX;
  point.y = e.pageY;
};

onMounted(() => {
  document.addEventListener("click", handleWindowClick);
});

onBeforeMount(() => {
  document.removeEventListener("click", handleWindowClick);
});
</script>

<template>
  <h2>Hook</h2>
  <p>当前鼠标点击时的坐标为: x: {{ point.x }} y: {{ point.y }}</p>
</template>

# 逻辑抽离

得益于setup就是一个普通的函数,也不需要管this指向的问题,因此我们可以轻易地将逻辑抽离出来,就像这样

// @/hooks/userPoint.js
import { onBeforeMount, onMounted, reactive } from "vue";

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

  const handleWindowClick = (e) => {
    point.x = e.pageX;
    point.y = e.pageY;
  };

  onMounted(() => {
    document.addEventListener("click", handleWindowClick);
  });

  onBeforeMount(() => {
    document.removeEventListener("click", handleWindowClick);
  });
  return point;
}
<script setup>
import usePoint from "@/hooks/usePoint";
let point = usePoint();
</script>

<template>
  <h2>Hook2</h2>
  <p>当前鼠标点击时的坐标为: x: {{ point.x }} y: {{ point.y }}</p>
</template>

# 总结

  • 什么是 hook 一个函数,把 setup 中使用 Compositon API 的代码进行了抽离,封装
  • hook 的优势 复用代码,让组件内的代码更清晰更易懂