一、什么是hook
hook本质是一个函数,把setup函数中使用的Composition API(组合式API)进行了封装,类似于vue中的mixin。
自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂。
我们用获取当前鼠标的坐标这个例子来说明:
二、未封装hook前的代码
<template>
<div>
<h3>当前鼠标的坐标为:x:{{ point.x }},y:{{ point.y }}</h3>
</div>
</template>
<script>
import { onBeforeUnmount, onMounted, reactive } from 'vue';
export default {
setup() {
let point = reactive({
x: 0,
y: 0
})
function savePoint(e) {
point.x = e.pageX
point.y = e.pageY
console.log(point.x, point.y);
}
onMounted(() => {
window.addEventListener('click', savePoint)
})
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint)
})
return {
point
}
}
}
</script>
三、封装后的代码
(1)组件中(PointView.vue)
<template>
<div>
<h3>当前鼠标的坐标为:x:{{ point.x }},y:{{ point.y }}</h3>
</div>
</template>
<script>
import usePoint from "@/hooks/usePoint";
export default {
setup() {
const point = usePoint()
return {
point
}
}
}
</script>
(2)hook中(usePoint.js)
import { onBeforeUnmount, onMounted, reactive } from 'vue';
// 获取鼠标当前坐标
export default function() {
// 数据
let point = reactive({
x: 0,
y: 0
})
// 方法
function savePoint(e) {
point.x = e.pageX
point.y = e.pageY
console.log(point.x, point.y);
}
onMounted(() => {
window.addEventListener('click', savePoint)
})
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint)
})
// 返回值
return point
}