概念
-
什么是hook?
-
本质是一个函数,把setup函数中使用的Composition API进行了封装。
-
类似于vue2.x中的mixin。(但是mixins会组件的配置项覆盖。vue3使用了自定义hooks替代mixnins,hooks本质上是函数,引入调用。)
-
-
自定义hook的优势:
- 复用代码, 让setup中的逻辑更清楚易懂。
功能演示
鼠标点击屏幕,获取坐标:
<template>
<h2>当前鼠标的坐标是:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import {onMounted, onBeforeUnmount,reactive} from 'vue'
export default {
name: 'Demo',
setup() {
let point = reactive({
x: 0,
y: 0
})
function savePoint(event) {
point.x = event.pageX;
point.y = event.pageY;
}
onMounted(() => {
window.addEventListener("click",savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener("click",savePoint)
})
return {
point,
}
},
}
</script>
然后改用使用 hooks,在 src 下新建 hooks 文件夹,增加 usePoint.js 命名规则通常为:use+xxx.js
import {reactive,onMounted,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(event.pageX,event.pageY)
}
//实现鼠标“打点”相关的生命周期钩子
onMounted(()=>{
window.addEventListener('click',savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return point
}
在 Demo.vue 中使用:
<template>
<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>
复用测试
Test.vue
<template>
<h2>我是Test组件</h2>
<h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
</template>
<script>
import usePoint from '../hooks/usePoint'
export default {
name:'Test',
setup(){
const point = usePoint()
return {point}
}
}
</script>