什么是hook函数?
本质就是一个函数,把setup函数中使用的Composition API进行封装
类似于vue2中minxi
自定义hook 的优势: 复用代码, 让setup 中的逻辑更清楚易懂。
创建一个hook文件夹,里面创建文件usePoint.js
import { onMounted , reactive, onBeforeUnmount} from 'vue';
export default function(){
let point = reactive({
x:0,
y:0
})
function savePoint(event){
point.x = event.pageX;
point.y = event.pageY;
console.log(`x轴:${point.x},y轴${point.y}`)
}
onMounted(()=>{
window.addEventListener('click',savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return point;
}
<template>
<div class="about">
<h2>当前鼠标点击的坐标 : {{point.x}} --- {{point.y}}</h2>
</div>
</template>
<script>
import usePoint from '../hook/usePoint'
export default{
name:'AboutView',
setup(){
const point = usePoint();
return {point};
}
}
</script>
如图:
?
|