hook就是将一些公共方法,公共的组建属性提取出去,封装成一个js文件,类似于mixin,
举例:页面上鼠标点击,获取鼠标坐标
demo.vue文件
<template>
<div>
<div>鼠标点击的位置:x:{{point.x}},y:{{point.y}} </div>
</div>
</template>
<script>
// import {ref} from 'vue'
import usePoint from './usePoint'
export default {
name: 'app1',
setup(){
let point = usePoint();
return {point}
}
}
</script>
usePoint.js文件
const { reactive, onMounted, onUnmounted } = require("vue");
export default function(){
//实现鼠标打点数据
let point = reactive({
x:0,
y:0
})
//实现鼠标打点的方法
function savePoint(event){
point.x = event.pageX;
point.y = event.pageY;
}
//初始化监听
onMounted(()=>{
window.addEventListener("click",savePoint)
})
// 卸载的时候移除监听
onUnmounted(()=>{
window.removeEventListener("click",savePoint)
})
return point;
}
说明:在vue文件内想要某个事件触发,但是这个事件又不止这一个地方需要,可能很多地方都需要,就封装在一个组件中,如上usePoint.js文件是封装的,然后在demo.vue内只需要引用一下,然后在setup内用变量接收一下即可