什么是hook?
本质是一个函数,把setup函数中使用的Composition API(组合式api)进行了封装
类似于vue2.x中的mixin
自定义hook的优势:
复用代码,让setup中的逻辑更清楚易懂
举个例子,通过在页面获取鼠标点击的坐标为例,来说明一下自定义hook的作用
新建文件: src/hooks/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(e.pageX, e.pageY)
}
onMounted(() => {
// 其中第一个参数是事件的类型(如'click 或 'mousedown')
// 第二个参数是事件触发后调用的函数
window.addEventListener('click', savePoint)
})
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint)
})
return point
}
在demo.vue中使用
先引入hook函数,然后调用函数即可
<template>
<!-- 测试使用hook来引入组件 -->
<h2>当前求和为:{{sum}}</h2>
<button @click="sum++">点我加1</button>
<hr>
<h2>当前鼠标点击的坐标为:x:{{point.x}} y:{{point.y}}</h2>
</template>
<script>
import {ref } from 'vue'
import usePoint from '../hooks/usePoint'
export default {
name: 'Demo',
setup() {
let sum = ref(0)
let point = usePoint()
return {
sum, point
}
}
}
</script>
所以其他组件也想用的时候,只需要3个步骤
1、引入:import usePoint from ‘…/hooks/usePoint’
2、接收:let point = usePoint()
3、暴露:return { point }
usePoint() 就起到了可以将外部封装的组合式api全部带进自己的setup里面,不用自己再写一遍,精准的体现了自定义hook的作用:将setup函数中使用的Composition API(组合式api)进行了封装
参考链接:https://blog.csdn.net/qq_41579104/article/details/122718672