概念
- 他类似于vue2中的
mixin
技术,用于封装可复用功能的函数 - 在我们写的hooks的文件中我们可以使用任何vue3的api
代码
我们一般会新建
src/hooks
文件夹来保存相应的hooks文件
收集用户点击页面的坐标
定义
import { ref, onMounted, onUnmounted } from "vue"
export default function useMousePosition() {
const x = ref(0)
const y = ref(0)
const updatePosition = (e) => {
x.value = e.pageX
y.value = e.pageY
}
// 挂在后绑定监听
onMounted(() => {
document.addEventListener("click", updatePosition)
})
// 卸载监听
onUnmounted(() => {
document.removeEventListener("clcik", updatePosition)
})
return { x, y }
}
使用
<script setup>
import useMousePosition from '../hooks/useMousePosition';
const {x,y} = useMousePosition()
</script>
<template>
<section>
<div>x轴的坐标{{x}}</div>
<div>y轴的坐标{{y}}</div>
</section>
</template>
当我们进行点击的时候,坐标就会进行相应的改变