自定义 hook 函数
使用 Vue3 的组合 API 封装的可复用的功能函数
自定义 hook 的作用类似于 vue2 中的 mixin 技术
自定义 Hook 的优势:很清楚复用功能代码的来源,更清楚易懂
需求 1: 收集用户鼠标点击的页面坐标
hooks/useMousePosition.ts
javascript
import { ref, onMounted, onUnmounted } from "vue";
/*
收集用户鼠标点击的页面坐标
*/
export default function useMousePosition() {
// 初始化坐标数据
const x = ref(-1);
const y = ref(-1);
// 用于收集点击事件坐标的函数
const updatePosition = (e) => {
x.value = e.pageX;
y.value = e.pageY;
};
// 挂载后绑定点击监听
onMounted(() => {
document.addEventListener("click", updatePosition);
});
// 卸载前解绑点击监听
onUnmounted(() => {
document.removeEventListener("click", updatePosition);
});
return { x, y };
}
vue
<template>
<h2>x: {{ x }}, y: {{ y }}</h2>
</template>
<script setup>
/*
在组件中引入并使用自定义 hook
自定义 Hook 的优势:很清楚复用功能代码的来源,更清楚易懂
*/
import useMousePosition from "./hooks/useMousePosition";
const { x, y } = useMousePosition();
</script>
<style scoped></style>